Skip to main content

React Native

Percept React Native SDK

1. Install​

npm install @perceptinsight/percept-react-native
or
yarn add @perceptinsight/percept-react-native

This package has dependency on @react-native-async-storage/async-storage, react-native-device-info and @notifee/react-native. To install, run the following commands:

npm install @react-native-async-storage/async-storage react-native-device-info @notifee/react-native
or
yarn add @react-native-async-storage/async-storage react-native-device-info @notifee/react-native

npx pod-install

2. Initialize Percept SDK​

import Percept from "@perceptinsight/percept-react-native";

await Percept.init("Your Project Token");

init method takes an optional initOptions param as second argument which can be used to configure auto tracked events. initOptions properties:

propertyrequiredtypedefault value
autoCaptureAppLifecycleEventsfalsebooleantrue
autoCaptureUnhandledExceptionsfalsebooleantrue
eventsFlushThresholdInSecondsfalsenumber10
autoTrackApiCallsfalsebooleanfalse
apiTrackingBlocklistfalsestring | string[][]
autoFlushBatchSizefalsenumber30
enableExperimentfalsebooleanfalse
experimentFetchedCbfalsefunctionundefined
experimentRefetchIntervalMinfalsenumberundefined

See what events are tracked by these

NOTE: This is an asynchronous call

3. Set user id​

After successfully initializing the SDK, On login set User id using the following function.

await Percept.setUserId('U1');

NOTE: This is an asynchronous call

4. Set user properties​

use setUserProperties method to set properties on the user profile created by setUserId

// first call this method
await Percept.setUserId('U1');

// sets user `isVerifiedAccount` property to true
Percept.setUserProperties({isVerifiedAccount: true})

We expose some default user property keys in PERCEPT_DEFAULT_USER_PROPERTIES. Please use them as this helps in standarization and usage in the Engage feature provided by Percept.

import Percept, {PERCEPT_DEFAULT_USER_PROPERTIES} from '@perceptinsight/percept-react-native'

// first call this method
await Percept.setUserId('U1');

// sets user `phone` property to '123456789' and `isVerifiedAccount` property to true
Percept.setUserProperties({[PERCEPT_DEFAULT_USER_PROPERTIES.PHONE]: 123456789, isVerifiedAccount: true})

5. Send Event​

Let's get started by sending event data. You can send an event from anywhere in your application. After initializing the library, Percept will automatically track some properties by default.

// Track only event-name
Percept.capture('Referral Banner Click');
// Track event-name with property
Percept.capture('Screen View', {'screenName': 'Homepage'});

6. Timing Events​

You can track the time it took any action to complete using timeEvent method. Calling this method will mark the start of the action and subsequent call to capture method will mark the end. The time duration is recorded in pi_timed_event_duration property.

// Start the time for the event 'Image Upload'
Percept.timeEvent('Image Upload');
// ... some time later. This call capture the 'Image Upload' event with 'pi_timed_event_duration' property
Percept.capture('Image Upload');

7. Set Global Property​

Set global property which will be passed with all subsequent events

await Percept.setGlobalProperty('global-property-key', 'value');

8. Set Multiple Global Property​

Call this method to bulk set multiple global properties

await Percept.setMultipleGlobalProperty([{key: 'global-prop-key-1', value: 'value 1'}, {key: 'global-prop-key-2', value: 'value 2'}, {key: 'global-prop-key-3', value: 'value 3'}]);

9. Remove Global Property​

Remove any previously set global property

await Percept.removeGlobalProperty('global-property-key');

10. Get all global properties​

Get all global properties

await Percept.getAllGlobalProperties();

11. Clear​

Call clear function on logout to delete all user related information

await Percept.clear()

Integrating Engage module​

Firebase messaging module is prereuisite for this. Kidnly follow the steps mentioned here​

Once you are done with FCM integration, follow the following steps to streamline push notification functionality and monitor their impact and attribution

1. Pass the fcm token received from Firebase to Percept​

  import messaging from '@react-native-firebase/messaging';

// get token from firebase messaging
const fcmToken = await messaging().getToken();
// set percept fcm token
if (fcmToken && fcmToken.length > 0) {
Percept.setUserProperties({
[PERCEPT_DEFAULT_USER_PROPERTIES.DEVICE_TOKEN]: fcmToken,
});
}

// update token passed to percept on token refresh
messaging().onTokenRefresh(token => {
Percept.setUserProperties({
[PERCEPT_DEFAULT_USER_PROPERTIES.DEVICE_TOKEN]: token,
});
});

NOTE: Do not pass fcm token to Percept SDK before calling Percept.setUserId​

2. Notify Percept sdk when app is in foreground when push notification was received​

    import messaging from '@react-native-firebase/messaging';
import Percept, {
PerceptCommForegroundHandler,
} from '@perceptinsight/percept-react-native';

messaging().onMessage(async remoteMesssage => {
PerceptCommForegroundHandler(remoteMesssage as any, {
piToken: YOUR_PERCEPT_KEY,
smallIcon: 'ic_notif_name', // mandatory. your notification icon asset name present in res folder
// Large icon Remote image
//largeIcon: 'https://my-cdn.com/users/123456.png',
// Large icon Local image
//largeIcon: require('../assets/user.jpg'),
// Large icon Absolute file path
//largeIcon: file:///xxxx/xxxx/xxxx.jpg,
// Large icon Android resource (mipmap or drawable)
//largeIcon: 'large_icon',
});
});

Notifying SDK when notification received in terminated state for better attribution​

Register the handler before calling runApp. Details for background fcm message handling-> https://rnfirebase.io/messaging/usage#background-application-state

  import messaging from '@react-native-firebase/messaging';
import {
PerceptCommBackgroundHandler
} from '@perceptinsight/percept-react-native';

// Register background handler. Read more here-> https://rnfirebase.io/messaging/usage#background--quit-state-messages
// Important information on iOS handling -> https://rnfirebase.io/messaging/usage#background-application-state
messaging().setBackgroundMessageHandler(async remoteMessage => {
PerceptCommBackgroundHandler(remoteMesssage as any, {
piToken: YOUR_PERCEPT_KEY,
smallIcon: 'ic_notif_name', // mandatory. your notification icon asset name present in res folder
// Large icon Remote image
//largeIcon: 'https://my-cdn.com/users/123456.png',
// Large icon Local image
//largeIcon: require('../assets/user.jpg'),
// Large icon Absolute file path
//largeIcon: file:///xxxx/xxxx/xxxx.jpg,
// Large icon Android resource (mipmap or drawable)
//largeIcon: 'large_icon',
});
});

Events auto tracked by sdk​

event nameinitOption key to controldescription
App OpenedautoCaptureAppLifecycleEventsTriggered when percept sdk is initialized
App ActiveautoCaptureAppLifecycleEventsTriggered when app comes to foreground
App BackgroundedautoCaptureAppLifecycleEventsTriggered when app goes to background
Application InstalledautoCaptureAppLifecycleEventsTriggered when app is installed for the first time
Application UpdatedautoCaptureAppLifecycleEventsTriggered when app is updated
Unhandled JS ErrorautoCaptureUnhandledExceptionsTriggered when some unhandled runtime error takes place in JS thread
$FetchautoTrackApiCallsTriggered when any api call is made

Custom app and device properties attached by SDK​

These properties are available in all events

propertydescription
pi_app_buildBuild number like "2.3.7" or "237"
pi_app_nameApplication name
pi_app_versionHuman friendly app version like "2.3.7"
pi_carrierNetwork operator name
pi_device_manufacturerDevice manufacturer. Ex. 'Google', 'Apple'
pi_device_nameDevice model name
pi_first_install_timeThe time at which the app was first installed, in milliseconds
pi_install_referrerOnly available on android. Gets the referrer string upon application installation. If the app was installed from https://play.google.com/store/apps/details?id=com.myapp&referrer=my_install_referrer the result will be "my_install_referrer"
pi_is_location_enabledBoolean to know whether location is enabled on device or not
pi_os_nameOperating system name like iOS or Android
pi_os_versionOperating system version "7.1.3"

Folowing properties are part of Unhandled JS Error event:​

propertydescription
pi_is_fatalFatal error boolean
pi_unhandled_error_eventStringified captured error object
pi_unhandled_error_nameError name
pi_unhandled_error_stackStringified error stack
pi_unhandled_error_messageError message
Property_nameDescription
pi_pn_isPNAttributedIs the current session PN triggered
pi_pn_campaignIdCampaignId associated with the notificaiton
pi_pn_campaignNameCampaignName associated with the notificaiton
pi_pn_campaignSourceCampaignSource associated with the notificaiton

Network calls tracking​

Network calls are tracked as $Fetch event. It is disabled by default and can be enabled by setting autoTrackApiCalls to true in init options. Percept Insight only tracks fetch/xhr calls and static resource calls are not tracked.
You can ask Percept Insight to not track certain api calls by passing the relevant url string/regex or string array in apiTrackingBlocklist parameter in init options.

Following properties are available as part of this event:

property
pi_fetch_url
pi_fetch_status_code
pi_fetch_request_type
pi_fetch_successful
pi_fetch_time_taken

Handling Experiments​

1. Enabling Experiments​

To enable experiment tracking, set the enableExperiment option to true in the initOptions. You can also specify a callback function to handle the experiment data when it is fetched.

const initOptions = {
enableExperiment: true,
experimentFetchedCb: (data) => {
const { experimentData, experimentUserType, isExperimentDataResolved } = data;
if (isExperimentDataResolved) {
console.log('Experiment data fetched:', experimentData);
} else {
console.log('Experiment data could not be resolved.');
}
},
experimentRefetchIntervalMin: 10, // Refetch experiment data every 10 minutes
};

Percept.init('Your Project Token', initOptions);

Note: The experimentRefetchIntervalMin option sets the interval in minutes for automatically refetching experiment data. The interval must be at least 5 minutes. If a value less than 5 is provided, it will be automatically set to 5 minutes and a warning will be logged.

2. Fetching Experiment Data​

You can fetch experiment data at any time using the getExperiment method. This method returns a promise that resolves to the variant data for the specified experiment.

const experimentName = 'example-experiment';
const variant = await Percept.getExperiment(experimentName);

if (variant) {
console.log(`User is in variant: ${variant}`);
} else {
console.log('No variant data available');
}

3. Refetching Experiment Data​

If you have set the experimentRefetchIntervalMs option, the SDK will automatically refetch the experiment data at the specified interval. You can also manually refetch the experiment data using the refetchExperiment method.

await Percept.refetchExperiment();

4. Getting All Active Experiments​

You can get all active experiments and their variants using the getAllActiveExperiments method.

const activeExperiments = await Percept.getAllActiveExperiments();
console.log('Active experiments:', activeExperiments);

5. Getting Experiment User Type​

You can get the user type for experiments using the getExperimentUserType method.

const userType = await Percept.getExperimentUserType();
console.log('Experiment user type:', userType);