Command palette

@yasinsensoy/native

React Native · APIs and utilities

Notifications

Notification API.

22 exports

Import

import {
  NOTIFICATION_ACTION_TASK,
  normalizeTrigger,
  Notifications,
  useNotificationResponse,
  useNotificationReceived,
  usePushToken,
} from "@yasinsensoy/native";

Notification API. Showing needs permission: Permissions.request("notifications") (Android 13+ and iOS).

NameTypeDescription
schedule(request: NotificationRequest) => Promise<string>Schedules a notification (shows it immediately without a trigger); returns its id. On Android scheduled ones survive a device reboot.
present(request: Omit<NotificationRequest, "trigger">) => Promise<string>Shows immediately.
cancel(id: string) => Promise<void>Cancels a scheduled notification (does not close a shown one: Notifications.dismiss).
cancelAll() => Promise<void>Cancels all scheduled notifications.
getScheduled() => Promise<ScheduledNotification[]>Scheduled notifications.
dismiss(id: string) => Promise<void>Removes a notification from the notification center.
dismissAll() => Promise<void>Removes all notifications from the notification center.
getPresented() => Promise<PresentedNotification[]>The ones visible in the notification center.
setBadge(count: number) => Promise<void>Badge on the app icon (iOS). On Android launchers compute the badge from the notifications themselves; the value is only stored.
getBadge() => Promise<number>The badge count last set with setBadge.
createChannel(options: ChannelOptions) => Promise<void>Creates/updates an Android channel (afterwards only the user can change its importance).
deleteChannel(id: string) => Promise<void>Deletes an Android channel and the user's settings for it.
getChannels() => Promise<NotificationChannel[]>The app's Android channels (empty on iOS).
setCategories(categories: readonly NotificationCategory[]) => Promise<void>Defines action button sets (replacing the previous ones).
setForegroundPresentation(options: ForegroundPresentation) => voidHow a notification arriving in the foreground is presented (default: all on).
getInitialResponse() => NotificationResponse | nullThe tap that opened the app (or the last tap that arrived with no listener). Every call returns the same value within the same JS session.
addReceivedListener(listener: (notification: NotificationContent) => void) => () => voidA notification arriving in the foreground.
addResponseListener(listener: (response: NotificationResponse) => void) => () => voidA tap on a notification or an action button.
canScheduleExactAlarms() => booleanAndroid: whether exact alarms can be used (ui.config notifications.android.exactAlarms and user permission). Always true on iOS.
openSettings(options?: { channel?: string; page?: "exactAlarms"; }) => Promise<void>Opens notification settings. Android: with channel, that channel's page; with "exactAlarms", the exact alarm permission page.
isPushAvailable() => booleanWhether remote notifications are enabled in the build (ui.config notifications).
getPushToken() => Promise<PushToken>Remote notification token. On iOS request notification permission first. Error codes: E_PUSH_DISABLED (off in settings), E_PUSH (registration failed; expected on a simulator and in unsigned builds).
deletePushToken() => Promise<void>Deletes the token (sign out); the next request gives a new token.
setBackgroundHandler(handler: NotificationBackgroundHandler | null) => voidHandler for actions that do not open the app (foreground: false): marking as read, sending an inline reply… It also runs while the app is closed (an Android headless JS task, an iOS background launch). Call it outside components, in the app's root file (index.js), so it is defined on a background launch too. Without a handler these taps arrive at Notifications.addResponseListener when the app opens.
addTokenListener(listener: (token: PushToken) => void) => () => voidThe token changed (iOS renews it on every launch; Android when FCM refreshes it).

Key of the headless JS task for background actions on the native side (Android).

NOTIFICATION_ACTION_TASK: 

Converts a trigger to the native format.

normalizeTrigger(trigger: NotificationTrigger): NormalizedTrigger

Listens to taps; the tap that opened the app arrives once too. Use it in the root component for navigation.

useNotificationResponse(listener: (response: NotificationResponse) => void): void

Examples

useNotificationResponse((response) => {
  if (response.notification.data.orderId) navigate("Order", response.notification.data);
});

Listens to notifications arriving in the foreground.

useNotificationReceived(listener: (notification: NotificationContent) => void): void

usePushToken

function

Remote notification token; obtained once permission is granted (enabled) and updated when it changes.

usePushToken({ enabled }?: { enabled?: boolean; }): {
    token: PushToken | null

Notification data: JSON values.

type NotificationData = Record<string, unknown>

When to show it:

  • { date }: a specific moment (once).
  • { seconds, repeats? }: this long from now; with repeats every seconds seconds (at least 60 for repeating on iOS).
  • { hour, minute, weekday? }: every day (or that day of the week) at that time. weekday 1 = Sunday … 7 = Saturday. Once with repeats: false.
NameTypeDefaultDescription
dateDate | numberMoment to show it (a Date or ms, epoch).({ /** Moment to show it (a `Date` or ms, epoch). */ date: Date | number; })
secondsnumberDelay in seconds.({ /** Delay in seconds. */ seconds: number; /** Repeat every `seconds` seconds. @defaultValue `false` */ repeats?: boolean; })
repeats?booleanfalseRepeat every seconds seconds.({ /** Delay in seconds. */ seconds: number; /** Repeat every `seconds` seconds. @defaultValue `false` */ repeats?: boolean; } | { /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday; every day if omitted. */ weekday?: number; /** Repeat every day/week. @defaultValue `true` */ repeats?: boolean; })
hournumberHour (0–23).({ /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday; every day if omitted. */ weekday?: number; /** Repeat every day/week. @defaultValue `true` */ repeats?: boolean; })
minutenumberMinute (0–59).({ /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday; every day if omitted. */ weekday?: number; /** Repeat every day/week. @defaultValue `true` */ repeats?: boolean; })
weekday?numberDay of the week: 1 = Sunday … 7 = Saturday; every day if omitted.({ /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday; every day if omitted. */ weekday?: number; /** Repeat every day/week. @defaultValue `true` */ repeats?: boolean; })

A notification to show.

NameTypeDefaultDescription
id?stringId; rescheduling with the same id replaces the previous one. Generated if not given.
title?stringTitle.
body?stringBody text.
subtitle?stringiOS subtitle; on Android a short text next to the title.
data?NotificationDataData returned when tapped.
trigger?NotificationTriggerTrigger; shown immediately if not given.
channel?string"default"Android channel.
category?stringCategory: action buttons (Notifications.setCategories).
group?stringGrouping key (iOS threadIdentifier, Android group).
badge?numberBadge count (on the iOS app icon; the notification's number on Android).
sound?boolean | stringtrueSound: false silent, a string for a custom sound file (in the iOS app bundle; on Android the sound is bound to the channel, ChannelOptions.sound).
color?stringAndroid: accent color (#rrggbb); the one in ui.config if omitted.
sticky?booleanAndroid: cannot be dismissed by swiping (for ongoing work).

A received/shown notification.

NameTypeDescription
idstringNotification id.
titlestring | nullTitle.
bodystring | nullBody text.
subtitle?string | nulliOS subtitle; on Android the short text next to the title.
dataNotificationDataData given when scheduling.
channel?stringAndroid channel.
category?stringCategory (action buttons).
group?stringGrouping key.
badge?numberBadge count.
remote?booleanWhether it is a remote notification (push).

A scheduled notification.

NameTypeDescription
triggerNormalizedTrigger | nullTrigger; null if unknown.
nextDatenumber | nullNext presentation (ms, epoch); null if unknown.
idstringNotification id.
titlestring | nullTitle.
bodystring | nullBody text.
subtitle?string | nulliOS subtitle; on Android the short text next to the title.
dataNotificationDataData given when scheduling.
channel?stringAndroid channel.
category?stringCategory (action buttons).
group?stringGrouping key.
badge?numberBadge count.
remote?booleanWhether it is a remote notification (push).

A notification in the notification center.

NameTypeDescription
datenumberWhen it was shown (ms, epoch).
idstringNotification id.
titlestring | nullTitle.
bodystring | nullBody text.
subtitle?string | nulliOS subtitle; on Android the short text next to the title.
dataNotificationDataData given when scheduling.
channel?stringAndroid channel.
category?stringCategory (action buttons).
group?stringGrouping key.
badge?numberBadge count.
remote?booleanWhether it is a remote notification (push).

A tap.

NameTypeDescription
notificationNotificationContentThe notification that was tapped.
actionIdstring"default" (the notification was tapped), "dismiss" (iOS, dismissed) or the action's id.
userText?stringText typed in an action with text input (input).

Trigger sent to the native side.

NameTypeDescription
type"date" | "interval" | "calendar"Trigger kind.
datenumberMoment (ms, epoch).({ /** Trigger kind. */ type: "date"; /** Moment (ms, epoch). */ date: number; })
secondsnumberDelay in seconds.({ /** Trigger kind. */ type: "interval"; /** Delay in seconds. */ seconds: number; /** Whether it repeats. */ repeats: boolean; })
repeatsbooleanWhether it repeats.({ /** Trigger kind. */ type: "interval"; /** Delay in seconds. */ seconds: number; /** Whether it repeats. */ repeats: boolean; } | { /** Trigger kind. */ type: "calendar"; /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday. */ weekday?: number; /** Whether it repeats. */ repeats: boolean; })
hournumberHour (0–23).({ /** Trigger kind. */ type: "calendar"; /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday. */ weekday?: number; /** Whether it repeats. */ repeats: boolean; })
minutenumberMinute (0–59).({ /** Trigger kind. */ type: "calendar"; /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday. */ weekday?: number; /** Whether it repeats. */ repeats: boolean; })
weekday?numberDay of the week: 1 = Sunday … 7 = Saturday.({ /** Trigger kind. */ type: "calendar"; /** Hour (0–23). */ hour: number; /** Minute (0–59). */ minute: number; /** Day of the week: 1 = Sunday … 7 = Saturday. */ weekday?: number; /** Whether it repeats. */ repeats: boolean; })

An action button.

NameTypeDefaultDescription
idstringAction id; arrives as NotificationResponse.actionId.
titlestringButton text.
destructive?booleanRed (iOS).
foreground?booleantrueOpens the app. With false the JS Notifications.setBackgroundHandler handler runs in the background without opening the app (even while it is closed): for actions like "Mark as read", "Reply".
authenticationRequired?booleaniOS: runs only when unlocked.
input?{ /** iOS: text of the send button. */ buttonTitle?: string; /** Hint in the empty field. */ placeholder?: string; /** Android: smart replies suggested by the system. @defaultValue `false` */ suggestions?: boolean; }Text input (quick reply): typed inside the notification on both platforms; the text arrives in NotificationResponse.userText.
dismiss?booleantrue` (`false` with text input)Android, background action: close the notification when pressed. For an action with text input the default is false: the notification stays (in the handler you can update it with Notifications.present using the same id, or close it with Notifications.dismiss). iOS always closes the notification.

A set of action buttons; chosen on a notification with category.

NameTypeDescription
idstringCategory id; given as category on a notification.
actionsreadonly NotificationAction[]Action buttons, in order.

Android channel importance.

type ChannelImportance = "min" | "low" | "default" | "high"

Android notification channel (Android 8+; ignored on iOS).

NameTypeDefaultDescription
idstringChannel id; given as channel on a notification.
namestringName shown in settings.
description?stringDescription shown in settings.
importance?ChannelImportance"high"
sound?boolean | stringfalse silent; a string is the name of a sound file under res/raw.
vibration?booleanVibrates.
lights?booleanBlinks the notification light.
showBadge?booleanShows a badge on the app icon.

Channel info.

NameTypeDescription
idstringChannel id.
namestring | nullName shown in settings.
descriptionstring | nullDescription shown in settings.
importanceChannelImportanceImportance.
showBadgebooleanShows a badge on the app icon.
vibrationbooleanVibrates.
soundbooleanPlays a sound.

Presentation of a notification arriving while the app is in the foreground. All default to true.

NameTypeDescription
banner?booleanShow it on top of the screen.
list?booleanAdd it to the notification center.
sound?booleanPlay the sound.
badge?booleanUpdate the badge.

PushToken

interface

Remote notification token: APNs on iOS, FCM on Android. Send this to your server.

NameTypeDescription
type"apns" | "fcm"Token kind.
tokenstringToken value.

Background action handler; when the returned Promise settles the system may suspend the app again (finish within ~25 s on iOS, 30 s on Android).

type NotificationBackgroundHandler = (response: NotificationResponse) => Promise<void> | void