React Native SDK Reference
Complete API reference for the PushEngage React Native SDK. For setup and installation, see the React Native Quickstart.
The SDK supports React Native 0.78+ with turbo module support. It uses FCM for Android and APNs for iOS.
Initialization
setAppId
Call this method in your root index.js before AppRegistry.registerComponent to set the app push ID in the SDK, registering the subscriber to that specific app push ID. The app push ID can be obtained from your PushEngage Dashboard Settings.
For more information, see the PushEngage React Native Reference.
This method must be called before using any other SDK features. It associates all subsequent operations with your specific PushEngage application.
Syntax
setAppId: (appId: string) => void
Parameters
appId: A String representing the app push ID to be set.
- This ID uniquely identifies the app in the push notification service.
- Must be a valid app push ID provided by PushEngage.
Usage
PushEngage.setAppId('YOUR_APP_PUSH_ID');
- Call this method early in your app's lifecycle, typically in your root component :::
enableLogging
Enable or disable logging for the PushEngage SDK.
Syntax
enableLogging: (shouldEnable: boolean) => void
Parameters
shouldEnable: Boolean indicating whether logging should be enabled (true) or disabled (false).
Usage
// Enable logging
PushEngage.enableLogging(true);
// Disable logging
PushEngage.enableLogging(false);
Notification Permission
requestNotificationPermission
The requestNotificationPermission method handles the crucial step of obtaining user consent for push notifications. This method presents the system permission prompt to the user and manages their response.
Without the necessary permissions, your app cannot deliver push notifications to the user. This function is crucial as it ensures that the user grants permission for notifications, allowing the app to deliver timely and relevant updates. If the user denies permission, the app will not be able to receive notifications.
Syntax
requestNotificationPermission: () => Promise<boolean>;
Returns
Promise resolving to:
true: Permission granted
false: Permission denied/rejected
Usage
const isGranted: boolean = await PushEngage.requestNotificationPermission();
Common Use Cases
- First time app-launch
// In your onboarding flow
async function onboardingComplete() {
const hasPermission = await PushEngage.requestNotificationPermission();
if (hasPermission) {
// Add your code implementation here
}
}
- Feature-specific permission
// When enabling a feature that needs notifications
async function enableDeliveryUpdates() {
const hasPermission = await PushEngage.requestNotificationPermission();
if (hasPermission) {
// Add your code implementation here
}
}
Request permission at an appropriate time in the user journey
Explain the benefits of push notifications before requesting :::
getNotificationPermissionStatus
Get the current notification permission status for the application.
Syntax
getNotificationPermissionStatus: () => string;
Returns
A string indicating the current notification permission state:
"granted": The application is authorized to post user notifications"denied": The application is not authorized to post user notifications"notYetRequested": (iOS only) The user has not yet made a choice regarding notification permissions
Usage
function checkPermissionStatus() {
const permissionStatus = PushEngage.getNotificationPermissionStatus();
switch (permissionStatus) {
case 'granted':
console.log('Notifications are allowed');
break;
case 'denied':
console.log('Notifications are denied');
break;
case 'notYetRequested':
console.log('Permission not yet requested'); // iOS only
break;
default:
console.log('Unknown permission status');
break;
}
}
Subscription
subscribe
Subscribe the user to push notifications. This method checks the current permission status and subscription state to determine the appropriate action.
Syntax
subscribe: () => Promise<void>;
Returns
Promise that resolves when subscribe operation completes successfully, or throws an error if the operation fails.
Usage
async function subscribeUser() {
try {
await PushEngage.subscribe();
console.log('User subscribed successfully');
} catch (error) {
console.error('Failed to subscribe user:', error);
}
}
unsubscribe
Unsubscribe the user from push notifications while preserving their subscription record. The user can be re-subscribed later using the subscribe() method.
Syntax
unsubscribe: () => Promise<void>;
Returns
Promise that resolves when unsubscribe operation completes successfully, or throws an error if the operation fails.
Usage
async function unsubscribeUser() {
try {
await PushEngage.unsubscribe();
console.log('User unsubscribed successfully');
} catch (error) {
console.error('Failed to unsubscribe user:', error);
}
}
getSubscriptionStatus
Check whether the user is currently subscribed to push notifications.
Syntax
getSubscriptionStatus: () => Promise<boolean>;
Returns
Promise resolving to:
true: User is subscribed to push notificationsfalse: User is not subscribed (unsubscribed or never subscribed)
Usage
async function checkSubscriptionStatus() {
try {
const isSubscribed = await PushEngage.getSubscriptionStatus();
if (isSubscribed) {
console.log('User is subscribed to push notifications');
} else {
console.log('User is not subscribed to push notifications');
}
} catch (error) {
console.error('Error checking subscription status:', error);
}
}
getSubscriptionNotificationStatus
Check whether the user can actually receive push notifications by verifying both subscription status and notification permission. The user can receive notifications only if they are subscribed AND the app has notification permission granted.
Syntax
getSubscriptionNotificationStatus: () => Promise<boolean>;
Returns
Promise resolving to:
true: User can receive notifications (subscribed AND permission granted)false: User cannot receive notifications (not subscribed or permission denied)
Usage
async function checkNotificationCapability() {
try {
const canReceiveNotifications =
await PushEngage.getSubscriptionNotificationStatus();
if (canReceiveNotifications) {
console.log('User can receive push notifications');
} else {
console.log('User cannot receive push notifications');
}
} catch (error) {
console.error('Error checking notification capability:', error);
}
}
Associate Profile ID
Profile IDs serve as unique identifiers for your subscribers, enabling you to recognize them across multiple devices. Each subscriber can be assigned just one profile ID. This ID should be a string, and you have the flexibility to use any value, such as an email or phone number.
getSubscriberId
Retrieve the unique subscriber ID for a user. PushEngage generates this ID for every user based on their subscription data. Sometimes, this ID is referred to as the 'subscriber_hash'. The subscriber ID remains consistent unless there's a change in the user's subscription.
Syntax
getSubscriberId: () => Promise<string | null>;
Returns
Promise resolving to:
string: The subscriber ID if the user is subscribednull: If the user is not subscribed
Usage
async function getSubscriberId() {
try {
const subscriberId = await PushEngage.getSubscriberId();
if (subscriberId) {
console.log('Subscriber ID:', subscriberId);
return subscriberId;
} else {
console.log('User is not subscribed or no valid ID available');
return null;
}
} catch (error) {
console.error('Error getting subscriber ID:', error);
return null;
}
}
addProfileId
This method allows you to set a profile ID for the current subscriber. If a profile ID already exists, it will be replaced with the new value.
Syntax
addProfileId: (profileId: string) => Promise<string | null>;
Parameters
profileId: Unique identifier for the subscriber
Returns
Promise resolving to:
string: Success/error message
null: If operation failed
Usage
async function setProfileId() {
try {
const profileId = '[email protected]';
const result = await PushEngage.addProfileId(profileId);
if (result) {
console.log('Profile ID set successfully:', result);
}
} catch (error) {
console.error('Failed to set profile ID:', error);
}
}
Common use cases
- Cross-device user identification
- Integration with CRM systems
Subscriber Details
getSubscriberDetails
This method retrieves subscriber details based on a provided list of strings, which can include city, state, country, device, device type, segments, etc.
Syntax
getSubscriberDetails: (values: string[] | null) =>
Promise<{ [key: string]: string | number | boolean } | null>;
Parameters
values: A list of strings that can contain any values from above mentioned fields.
- Specify which subscriber details you want to retrieve.
- Can include fields like city, state, country, device type, segments, etc.
Returns
Promise resolving to:
{ [key: string]: string | number | boolean }: Object containing subscriber detailsnull: If subscriber details cannot be retrieved
Usage
async function fetchSubscriberDetails() {
try {
const subscriberAttributes = [
'city',
'device',
'host',
'user_agent',
'has_unsubscribed',
'device_type',
'timezone',
'country',
'ts_created',
'state',
];
const details = await PushEngage.getSubscriberDetails(subscriberAttributes);
if (details) {
console.log('City:', details.city);
console.log('Device:', details.device);
console.log('Country:', details.country);
}
} catch (error) {
console.error('Failed to get subscriber details:', error);
}
}
Available Fields
| Field | Type | Description |
|---|---|---|
city | string | Subscriber's city |
state | string | Subscriber's state or region |
country | string | Subscriber's country |
device | string | Device name |
device_type | string | Device type (e.g., mobile, tablet) |
user_agent | string | App user agent string |
host | string | Host identifier |
timezone | string | Subscriber's timezone |
has_unsubscribed | boolean | Whether the subscriber has unsubscribed |
ts_created | string | ISO 8601 timestamp of subscription creation |
segments | array | Segment IDs the subscriber belongs to |
Segments
Segments are used to group subscribers so that you can send personalized notifications. Segments can be created based on attributes, categories, and more. Each subscriber can belong to up to 50 segments.
Where to create
You can create and manage segments in the PushEngage Dashboard or using the rest APIs. The dashboard provides an intuitive interface to set up various types of campaigns, define triggers, and customize the notification content.
- Log in to your PushEngage Dashboard.
- Navigate to the Audience section.
- Select Segments and click Create a New Segment.
- Define the segment name and criteria and save it.
addSegment
This method enables you to add the current subscriber to segments.
Syntax
addSegment: (segments: string[]) => Promise<string | null>;
Parameters
segments: A list of segments to be added.
Returns
Promise resolving to:
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function addToSegments() {
try {
const segments = ['premium_users', 'active_30d', 'mobile_app'];
const result = await PushEngage.addSegment(segments);
if (result) {
console.log('Segments added:', result);
} else {
console.log('Failed to add segments');
}
} catch (error) {
console.error('Error adding segments:', error);
}
}
addDynamicSegment
This method enables you to add the current subscriber to a segment for a specified duration, measured in days. After this period, the segment will be automatically removed from the subscriber.
Syntax
addDynamicSegment: (segments: { name: string; duration: number }[]) =>
Promise<string | null>;
Parameters
segments: A list of segment objects representing dynamic segments to be added.
Returns
Promise resolving to:
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function addDynamicSegments() {
try {
const segments = [
{ name: 'trial_users', duration: 30 },
{ name: 'new_customers', duration: 90 },
];
const result = await PushEngage.addDynamicSegment(segments);
if (result) {
console.log('Dynamic segments added:', result);
} else {
console.log('Failed to add dynamic segments');
}
} catch (error) {
console.error('Error adding dynamic segments:', error);
}
}
removeSegment
This method allows you to remove the current subscriber from segments.
Syntax
removeSegment: (segments: string[]) => Promise<string | null>;
Parameters
segments: The list of segment to be removed.
Returns
Promise resolving to:
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function removeFromSegments() {
try {
const segments = ['segment1', 'segment2', 'segment3'];
const result = await PushEngage.removeSegment(segments);
if (result) {
console.log('Segments removed:', result);
} else {
console.log('Failed to remove segments');
}
} catch (error) {
console.error('Error removing segments:', error);
}
}
Attributes
Attributes are key-value pairs that allow you to store additional information about your subscribers. You can utilize attributes to segment your subscribers and send personalized notifications. Each subscriber can have a maximum of 50 attributes. The key of an attribute can be up to 64 characters long, and the value can be up to 128 characters long in the case of a string.
You first need to create attributes before using them. You can create them from the PushEngage Dashboard.
addSubscriberAttributes
Use this method to add or update attributes for a subscriber. If an attribute with the specified key already exists, the existing value will be replaced.
Syntax
addSubscriberAttributes: (attributes: { [key: string]: string }) =>
Promise<string | null>;
Parameters
attributes: Object containing key-value pairs of attributes.
Returns
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function addAttributes() {
try {
const attributes = {
age: '25',
height: '6.1',
plan: 'premium',
};
const result = await PushEngage.addSubscriberAttributes(attributes);
if (result) {
console.log('Attributes added:', result);
} else {
console.log('Failed to add attributes');
}
} catch (error) {
console.error('Error adding attributes:', error);
}
}
setSubscriberAttributes
This method allows you to set attributes for a subscriber, replacing any previously associated attributes. Use this method when you need to entirely reset the attributes with new values.
Syntax
setSubscriberAttributes: (attributes: { [key: string]: string }) =>
Promise<string | null>;
Parameters
attributes: Object containing key-value pairs of attributes to set.
Returns
Promise resolving to:
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function setAttributes() {
try {
const attributes = {
age: '30',
height: '5.9',
plan: 'basic',
};
const result = await PushEngage.setSubscriberAttributes(attributes);
if (result) {
console.log('Attributes set:', result);
} else {
console.log('Failed to set attributes');
}
} catch (error) {
console.error('Error setting attributes:', error);
}
}
getSubscriberAttributes
Retrieve the attributes associated with the current subscriber using this method.
Syntax
getSubscriberAttributes: () =>
Promise<{ [key: string]: string | number | boolean } | null>;
Returns
Promise resolving to:
{ [key: string]: string | number | boolean }: Object containing subscriber attributes
null: If attributes cannot be retrieved
Usage
async function getSubscriberAttributes() {
try {
const attributes = await PushEngage.getSubscriberAttributes();
if (attributes) {
console.log('Subscriber attributes:', attributes);
} else {
console.log('No attributes found');
}
} catch (error) {
console.error('Error fetching attributes:', error);
}
}
deleteSubscriberAttributes
This method allows you to remove one or more attributes from the current subscriber. Provide an array of attribute names you wish to remove. Passing an empty array will result in the removal of all the subscriber's attributes.
Syntax
deleteSubscriberAttributes: (attributes: string[]) => Promise<string | null>;
Parameters
attributes: Array of attribute names to delete.
Returns
Promise resolving to:
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function removeAttributes() {
try {
const attributes = ['age', 'height'];
const result = await PushEngage.deleteSubscriberAttributes(attributes);
if (result) {
console.log('Attributes deleted:', result);
} else {
console.log('Failed to delete attributes');
}
} catch (error) {
console.error('Error deleting attributes:', error);
}
}
Automated Notifications
Automated notifications include all types of triggered campaigns, such as cart abandonment, price drop, back in stock, and browse abandonment. By default, automated notifications are enabled for all subscribers.
automatedNotification
This method allows you to enable/disable automated notifications for the current subscriber.
Syntax
automatedNotification: (status: boolean) => Promise<string | null>;
Parameters
status: true to enable the trigger campaign for this subscriber, false to disable it.
Returns
Promise resolving to:
string:
Success: Confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
Enable Automated Notifications
await PushEngage.automatedNotification(true);
Disable Automated Notifications
await PushEngage.automatedNotification(false);
For a reusable pattern:
async function toggleAutomatedNotifications(enable: boolean) {
try {
const result = await PushEngage.automatedNotification(enable);
if (result) {
console.log('Automated notifications updated:', result);
}
} catch (error) {
console.error('Error updating automated notifications:', error);
}
}
Triggered Campaigns
Triggered campaigns are predefined notifications that are automatically sent to users when they perform certain actions or meet specific conditions. For example, a Custom Trigger Campaign detects your visitor's behavior to send automated push notifications to the right person at the right time. Browse Abandonment campaigns send targeted messages to convert visitors who viewed certain pages, such as product pages or feature pages. Cart Abandonment campaigns help recover lost sales and quickly boost revenue with automatically triggered abandon cart push notifications. Price Drop campaigns re-engage your customers and increase conversion using Price Drop Alert Campaigns. Back in Stock Alert campaigns re-engage your customers and increase conversion using Inventory Alert Campaigns.
sendTriggerEvent
Detect your user's behavior to send automated push notifications to the right person at the right time.
Where to Create
You can create and manage triggered campaigns in the PushEngage Dashboard. The dashboard provides an intuitive interface to set up various types of campaigns, define triggers, and customize the notification content.
- Log in to your PushEngage Dashboard.
- Navigate to the Campaign section.
- Select Triggered Campaigns and click Create New Triggered Campaign.
- Select from either of the following options:
- Custom Trigger Campaign
- Browse Abandonment
- Cart Abandonment
- Define the trigger conditions and customize the notification content.
Syntax
sendTriggerEvent: (trigger: {
[key: string]: string | Record<string, string>;
}) => Promise<string | null>;
Parameters
trigger: The TriggerCampaign object representing the campaign event to be triggered.
Returns
Promise resolving to:
string:
Success: Trigger confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
async function triggerCampaign() {
try {
const trigger = {
campaignName: 'Welcome',
eventName: 'user_signup',
referenceId: '12345',
data: {
plan: 'premium',
source: 'mobile',
},
};
const result = await PushEngage.sendTriggerEvent(trigger);
if (result) {
console.log('Trigger campaign result:', result);
}
} catch (error) {
console.error('Failed to trigger campaign:', error);
}
}
campaignName and eventName can be found in the PushEngage Dashboard for the respective trigger campaign.
addAlert
Re-engage your customers and increase conversion using Price Drop Alert Campaigns and Inventory Alert Campaigns.
Where to Create
You can create and manage triggered alerts in the PushEngage Dashboard. The dashboard provides an intuitive interface to set up various types of campaigns, define triggers, and customize the notification content.
- Log in to your PushEngage Dashboard.
- Navigate to the Campaign section.
- Select Triggered Campaigns and click Create New Triggered Campaign.
- Select from either of the following options:
- Price Drop
- Back in Stock Alert
- Define the trigger conditions and customize the notification content.
Syntax
addAlert: (alert: { [key: string]: string | number | undefined }) =>
Promise<string | null>;
Parameters
alert: The TriggerAlert object representing the alert to be added.
Returns
Promise resolving to:
string:
Success: Alert confirmation messageError: Error message describing what went wrong
null: If operation failed
Usage
Price Drop
async function addPriceDropAlert() {
try {
const alert = {
type: 'priceDrop',
productId: 'prod_123',
link: 'https://example.com/product/123',
price: 99.99,
alertPrice: 89.99, // Optional: target price for alert; defaults to price if not set
};
const result = await PushEngage.addAlert(alert);
if (result) {
console.log('Price drop alert added:', result);
}
} catch (error) {
console.error('Failed to add alert:', error);
}
}
Back in Stock Alert
async function addInventoryAlert() {
try {
const alert = {
type: 'inventory',
productId: 'prod_123',
link: 'https://shop.com/product/123',
price: 99.99,
};
const result = await PushEngage.addAlert(alert);
if (result) {
console.log('Inventory alert added:', result);
}
} catch (error) {
console.error('Failed to add alert:', error);
}
}
Goal Tracking
Goal Tracking will help you assign conversion goals & value to your notification campaigns. You can set up a default goal and have it integrated for all your campaigns.
sendGoal
Where to Enable
You can enable/disable goal tracking in the PushEngage Dashboard. The dashboard provides an intuitive interface to set up tracking method, tracking duration, goal name and currency.
- Log in to your PushEngage Dashboard.
- Navigate to the Analytics section.
- Select Goal Tracking and tick Enable Goal Tracking.
Syntax
sendGoal: (goal: { [key: string]: string | number }) => Promise<string | null>;
Parameters
goal: Goal object representing the goal to be tracked.
Returns
Promise resolving to:
string:
Success: Goal tracking confirmationError: Error message describing what went wrong
null: If operation failed
Usage
async function sendGoal() {
try {
const goal = {
name: 'revenue',
count: 1,
value: 10,
};
const result = await PushEngage.sendGoal(goal);
if (result) {
console.log('Goal tracked:', result);
} else {
console.log('Failed to track goal');
}
} catch (error) {
console.error('Error tracking goal:', error);
}
}
name can be found in the PushEngage Dashboard under the Goal Tracking section.
Deep Linking
onValueChanged
Listen for deep link events and handle them in your application. A deep link can be a custom URL scheme or a standard HTTPS/HTTP URL. Tapping these links routes users directly to the desired content.
The deep linking functionality allows you to:
- Handle custom URL schemes
- Process universal links (HTTP/HTTPS URLs)
- Navigate users to specific screens based on notification interactions
- Pass custom data through notifications
Syntax
readonly onValueChanged: EventEmitter<{
deepLink: string;
data: { [key: string]: string };
}>
Returns
type DeepLinkData = {
deepLink: string; // The deep link URL/string
data: Record<string, string>; // Additional data payload
};
Usage
import { type EventSubscription } from 'react-native';
const listenerSubscription = React.useRef<null | EventSubscription>(null);
React.useEffect(() => {
listenerSubscription.current = PushEngage.onValueChanged((data) => {
console.log('Deep link:', data.deepLink);
console.log('Data:', data.data);
});
return () => {
listenerSubscription.current?.remove();
listenerSubscription.current = null;
};
}, []);
Common use cases
- E-commerce apps: Linking directly to product pages or carts.
- Content platforms: Linking to specific articles or videos.
- Social apps: Linking directly to user profiles or posts.
Implement fallback behavior for invalid deep links
Test deep links across different app states (foreground, background, terminated) :::
Utilities
getSdkVersion
Retrieves the current version of the PushEngage React Native SDK, returning a string that represents the SDK's current version.
Syntax
getSdkVersion: () => string;
Returns
A String representing the current version of the PushEngage React Native SDK.
Usage
PushEngage.getSdkVersion();
setSmallIconResource
Sets the resource name of the small icon used for notifications. The small icon appears in the status bar when a notification is displayed.
This method only has effect on Android. On iOS it is a no-op. :::
Syntax
setSmallIconResource: (resourceName: string) => Promise<void>;
Parameters
resourceName: A string representing the resource name of the small icon.
Usage
async function setNotificationIcon() {
if (Platform.OS === 'android') {
try {
await PushEngage.setSmallIconResource('your_icon_name');
console.log('Small icon set successfully');
} catch (error) {
console.error('Failed to set small icon:', error);
}
}
}
It is recommended to set a valid resource name to ensure proper display of notifications. If an invalid resource name is provided, the default bell icon specified by the PushEngage library will be used.