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 and react-native-device-info. To install, run the following commands:

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

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

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 opened from push notification for proper attribution

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

// app was in quit state when notification arrived and click on notification opened the app
messaging()
.getInitialNotification()
.then(async remoteMesssage => {
Percept.trackPn(
remoteMesssage as any,
PERCEPT_PN_ATTRIBUTION_STATE.TERMINATED,
);
});

// app was in background when notification arrived and click on notification opened the app
messaging().onNotificationOpenedApp(async remoteMesssage => {
Percept.trackPn(
remoteMesssage as any,
PERCEPT_PN_ATTRIBUTION_STATE.BACKGROUND,
);
});

// message listener foreground. app was in foreground when notification arrived
messaging().onMessage(async remoteMesssage => {
Percept.trackPn(
remoteMesssage as any,
PERCEPT_PN_ATTRIBUTION_STATE.FOREGROUND,
);
});

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 {
CapturePerceptCommRequest,
PerceptCommunicationState,
} from '@perceptinsight/percept-react-native';

messaging().setBackgroundMessageHandler(async remoteMessage => {
CapturePerceptCommRequest(
PerceptCommunicationState.COMMUNICATION_RECEIVED,
remoteMessage,
PERCEPT_API_KEY,
);
});

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