PageSense React Native — SDK Functions Reference

PageSense React Native — SDK Functions Reference

Overview  

This document covers the JavaScript wrapper (PageSenseSDKWrapper.js) which is shared across both the Android and iOS React Native integrations. The wrapper provides a unified JavaScript interface for interacting with the PageSense SDK through the React Native Native Bridge, abstracting away platform-specific native module differences.

Creating the JavaScript Wrapper  

Create the wrapper file at the following path from the project root:
  1. src/sdk/PageSenseSDKWrapper.js
  2. javascript
  3. import { NativeModules } from 'react-native';
  4. const { PageSenseSDKModule } = NativeModules;
  5. export const GoalProperty = Object.freeze({
  6.   REVENUE: 'revenue',
  7. });
  8. const VALID_GOAL_PROPERTIES = new Set(Object.values(GoalProperty));
  9. class PageSenseSDKWrapper {
  10.   constructor() {}
  11.   async initialiseSDK(accountId, sdkKey, projectName) {
  12.     try {
  13.       this._validateString(accountId, 'accountId');
  14.       this._validateString(sdkKey, 'sdkKey');
  15.       this._validateString(projectName, 'projectName');
  16.       const result = await PageSenseSDKModule.initialiseSDK(accountId, sdkKey, projectName);
  17.       return result === true;
  18.     } catch (error) {
  19.       console.log('[PageSenseSDK] initialiseSDK error:', error);
  20.       return false;
  21.     }
  22.   }
  23.   async activateExperimentByContext(experimentName, userContext) {
  24.     try {
  25.       this._validateString(experimentName, 'experimentName');
  26.       this._validateUserContext(userContext);
  27.       const safeUserContext = {
  28.         userId: userContext.userId,
  29.         userAttributes: userContext.userAttributes || {},
  30.       };
  31.       const variation = await PageSenseSDKModule.activateExperimentByContext(
  32.         experimentName,
  33.         safeUserContext,
  34.       );
  35.       return variation ?? null;
  36.     } catch (error) {
  37.       console.log('[PageSenseSDK] activateExperimentByContext error:', error);
  38.       return null;
  39.     }
  40.   }
  41.   async getVariationNameByContext(experimentName, userContext) {
  42.     try {
  43.       this._validateString(experimentName, 'experimentName');
  44.       this._validateUserContext(userContext);
  45.       const safeUserContext = {
  46.         userId: userContext.userId,
  47.         userAttributes: userContext.userAttributes || {},
  48.       };
  49.       const variation = await PageSenseSDKModule.getVariationNameByContext(
  50.         experimentName,
  51.         safeUserContext,
  52.       );
  53.       return variation ?? null;
  54.     } catch (error) {
  55.       console.log('[PageSenseSDK] getVariationNameByContext error:', error);
  56.       return null;
  57.     }
  58.   }
  59.   trackGoalByContext(goalName, userContext, goalProperties) {
  60.     try {
  61.       this._validateString(goalName, 'goalName');
  62.       this._validateUserContext(userContext);
  63.       const safeUserContext = {
  64.         userId: userContext.userId,
  65.         userAttributes: userContext.userAttributes || {},
  66.       };
  67.       if (goalProperties === undefined) {
  68.         PageSenseSDKModule.trackGoalByContext(goalName, safeUserContext);
  69.       } else {
  70.         this._validateGoalPropertiesNonEmpty(goalProperties);
  71.         PageSenseSDKModule.trackGoalWithPropertiesByContext(
  72.           goalName,
  73.           safeUserContext,
  74.           goalProperties,
  75.         );
  76.       }
  77.     } catch (error) {
  78.       console.log('[PageSenseSDK] trackGoalByContext error:', error);
  79.     }
  80.   }
  81.   _validateString(param, paramName) {
  82.     if (typeof param !== 'string' || param.trim() === '') {
  83.       throw new Error(`[PageSenseSDK] Invalid ${paramName}: must be a non-empty string`);
  84.     }
  85.   }
  86.   _validateAttributes(attributes) {
  87.     if (attributes === undefined || attributes === null) return;
  88.     if (typeof attributes !== 'object' || Array.isArray(attributes)) {
  89.       throw new Error('[PageSenseSDK] attributes must be a key-value object');
  90.     }
  91.     for (const key in attributes) {
  92.       if (typeof key !== 'string' || key.trim() === '') {
  93.         throw new Error('[PageSenseSDK] Invalid attribute key: must be a non-empty string');
  94.       }
  95.       const value = attributes[key];
  96.       if (typeof value !== 'string') {
  97.         throw new Error(`[PageSenseSDK] Invalid value for attribute "${key}". Allowed type: string`);
  98.       }
  99.     }
  100.   }
  101.   _validateUserContext(userContext) {
  102.     if (
  103.       userContext === undefined ||
  104.       userContext === null ||
  105.       typeof userContext !== 'object' ||
  106.       Array.isArray(userContext)
  107.     ) {
  108.       throw new Error('[PageSenseSDK] userContext must be a valid object');
  109.     }
  110.     this._validateString(userContext.userId, 'userContext.userId');
  111.     if (userContext.userAttributes !== undefined && userContext.userAttributes !== null) {
  112.       this._validateAttributes(userContext.userAttributes);
  113.     }
  114.   }
  115.   _validateGoalPropertiesNonEmpty(goalProperties) {
  116.     if (goalProperties === null) {
  117.       throw new Error(
  118.         '[PageSenseSDK] goalProperties cannot be null. Omit the argument for goals without properties.',
  119.       );
  120.     }
  121.     if (typeof goalProperties !== 'object' || Array.isArray(goalProperties)) {
  122.       throw new Error('[PageSenseSDK] goalProperties must be a key-value object');
  123.     }
  124.     const keys = Object.keys(goalProperties);
  125.     if (keys.length === 0) {
  126.       throw new Error(
  127.         '[PageSenseSDK] goalProperties cannot be empty. Omit the argument for goals without properties.',
  128.       );
  129.     }
  130.     for (const key of keys) {
  131.       if (!VALID_GOAL_PROPERTIES.has(key)) {
  132.         throw new Error(
  133.           `[PageSenseSDK] Invalid goal property key "${key}". ` +
  134.             `Must be one of: ${Array.from(VALID_GOAL_PROPERTIES).join(', ')}`,
  135.         );
  136.       }
  137.       const value = goalProperties[key];
  138.       if (typeof value !== 'string') {
  139.         throw new Error(
  140.           `[PageSenseSDK] Invalid value for goal property "${key}". Allowed type: string`,
  141.         );
  142.       }
  143.     }
  144.   }
  145. }
  146. export default new PageSenseSDKWrapper();

SDK Functions  

initialiseSDK  

Initialises the PageSense SDK and creates the PageSenseClient instance. Must be called once during application startup before any other SDK function is used.

Method Signature

javascript
async initialiseSDK(accountId, sdkKey, projectName)

Parameters

Parameter
Type
Required
Description
accountId
string
Yes
PageSense account identifier.
sdkKey
string
Yes
SDK key used for authentication.
projectName
string
Yes
Name of the PageSense project.

Return Type

Promise<boolean> — Returns true if the SDK initialised successfully, false if initialisation failed.
Example
  1. javascript
  2. useEffect(() => {
  3.   async function initializeSDK() {
  4.     try {
  5.       const result = await PageSenseSDKWrapper.initialiseSDK(
  6.         'PAGESENSE_ACCOUNT_ID',
  7.         'PAGESENSE_SDK_KEY',
  8.         'PAGESENSE_PROJECT_NAME',
  9.       );
  10.       setSdkReady(true);
  11.     } catch (error) {
  12.       setSdkReady(true);
  13.     }
  14.   }
  15.   initializeSDK();
  16. }, []);
Notes
  • Initialise the SDK only once per application lifecycle for a project.
  • The application UI should not be blocked if SDK initialisation fails. Always allow the app to proceed even if the SDK fails.
activateExperimentByContext  
Activates a FullStack experiment for the user using PageSenseUserContext and returns the variation assigned to the user. Sends an impression event to PageSense and persists the visitor assignment.

Method Signature
javascript
async activateExperimentByContext(experimentName, userContext)

Parameters
Parameter
Type
Required
Description
experimentName
string
Yes
Name of the experiment configured in PageSense.
userContext
object
Yes
User context object containing userId and optional userAttributes.
userContext.userId
string
Yes
Unique identifier for the user.
userContext.userAttributes
object
No
Key-value pairs of user attributes used for audience targeting. All keys and values must be strings.

Return Type
Promise<string|null> — Returns the variation name assigned to the user, or null if no variation is assigned or an error occurs.
Example
  1. javascript
  2. const userContext = {
  3.   userId: 'USER_ID',
  4.   userAttributes: {
  5.     DeviceType: 'Phone',
  6.     OS: 'Android',
  7.     OSVersion: '14',
  8.     DeviceModel: 'Pixel 8 Pro',
  9.   },
  10. };
  11. const variation = await PageSenseSDKWrapper.activateExperimentByContext(
  12.   'EXPERIMENT_NAME',
  13.   userContext,
  14. );
  15. switch (variation) {
  16.   case 'Original':    setButtonColor('#4F46E5'); break;
  17.   case 'Variation 1': setButtonColor('#EF4444'); break;
  18.   case 'Variation 2': setButtonColor('#16A34A'); break;
  19.   default:            setButtonColor('#6B7280');
  20. }

Notes

  • Call this function when the screen loads to ensure users are allocated to the correct variation immediately.
  • Always handle the null return by applying a safe default UI fallback.
getVariationNameByContext  
Retrieves the variation assigned to a user using PageSenseUserContext without activating the experiment. Does not send an impression event and does not persist the visitor assignment.
Use this function when you need to check the variation without recording the visit, for example in logging or conditional logic outside of the main experiment flow.

Method Signature
javascript
async getVariationNameByContext(experimentName, userContext)

Parameters
Parameter
Type
Required
Description
experimentName
string
Yes
Name of the experiment configured in PageSense.
userContext
object
Yes
User context object containing userId and optional userAttributes.
userContext.userId
string
Yes
Unique identifier for the user.
userContext.userAttributes
object
No
Key-value pairs of user attributes. All keys and values must be strings.

Return Type
Promise<string|null> — Returns the variation name assigned to the user, or null if no variation is found or an error occurs.
Example
  1. javascript
  2. const variation = await PageSenseSDKWrapper.getVariationNameByContext(
  3.   'EXPERIMENT_NAME',
  4.   userContext,
  5. );
  6. console.log('Variation Name:', variation);
Notes
  • Unlike activateExperimentByContext, this function does not send an impression to PageSense and does not allocate the user to a variation.
trackGoalByContext  
Tracks a goal event using PageSenseUserContext. Supports two calling styles depending on whether the goal has associated properties.

Without goal properties — use for FullStack Custom Event Goals:
javascript
trackGoalByContext(goalName, userContext)

With goal properties — use for Revenue Goals:
javascript
trackGoalByContext(goalName, userContext, goalProperties)

Parameters
Parameter
Type
Required
Description
goalName
string
Yes
Name of the goal configured in PageSense.
userContext
object
Yes
User context object containing userId and optional userAttributes.
userContext.userId
string
Yes
Unique identifier for the user.
userContext.userAttributes
object
No
Key-value pairs of user attributes. All keys and values must be strings.
goalProperties
object
No
Goal properties object. Keys must be from GoalProperty constants. Must be non-empty if provided.

Return Type
void
Example — Tracking a Goal Without Properties
  1. javascript
  2. function handleSubmitButton() {
  3.   const userContext = {
  4.     userId: 'USER_ID',
  5.     userAttributes: { DeviceType: 'Phone', OS: 'Android' },
  6.   };
  7.   PageSenseSDKWrapper.trackGoalByContext('GOAL_NAME', userContext);
  8. }
Example — Tracking a Revenue Goal
  1. javascript
  2. import PageSenseSDKWrapper, { GoalProperty } from './src/sdk/PageSenseSDKWrapper';
  3. function handleCompletePurchase(purchaseAmountInDollars) {
  4.   const userContext = {
  5.     userId: 'USER_ID',
  6.     userAttributes: { DeviceType: 'Phone', OS: 'Android' },
  7.   };
  8.   // Convert dollars to cents: $100.50 → "10050"
  9.   const revenueInCents = String(Math.round(purchaseAmountInDollars * 100));
  10.   const goalProperties = {
  11.     [GoalProperty.REVENUE]: revenueInCents,
  12.   };
  13.   PageSenseSDKWrapper.trackGoalByContext('PURCHASE_GOAL_NAME', userContext, goalProperties);
  14. }
  15. handleCompletePurchase(100.50);

Notes

  • If goalProperties is provided, it must be a non-empty object. For goals without properties, omit the argument entirely — do not pass null or an empty object.
  • Revenue values must be passed as a string in cents. Multiply the dollar amount by 100 and round to the nearest integer.
  • Trigger goal tracking immediately after the specific user action or event completes successfully.
GoalProperty Constants  
The GoalProperty constants are exported from PageSenseSDKWrapper.js and must be used as keys in the goalProperties object instead of hard-coded strings.
javascript
import { GoalProperty } from './src/sdk/PageSenseSDKWrapper';
JS Constant
String Value
Android Native Constant
iOS Native Enum Case
Purpose
GoalProperty.REVENUE
"revenue"
GoalProperty.REVENUE
GoalProperty.revenue
Revenue amount in cents, used for Revenue Goals

How GoalProperty Keys Travel Across the Bridge  
  • Android — The native Kotlin module maps each string key to the matching GoalProperty enum constant using a lookup against GoalProperty.<CONSTANT>.value, producing a HashMap<GoalProperty, String> that is passed to the SDK.
  • iOS — The native Swift module maps each string key to the matching GoalProperty enum case using GoalProperty(rawValue:), producing a [GoalProperty: String] dictionary that is passed to the SDK.
JavaScript: { [GoalProperty.REVENUE]: "10050" }
                     ↓
           String key "revenue" travels across bridge
                     ↓
Android:   HashMap { GoalProperty.REVENUE → "10050" }
iOS:       [GoalProperty.revenue: "10050"]

PageSenseUserContext Structure  
  1. javascript
  2. const userContext = {
  3.   userId: 'USER_ID',            // Required — non-empty string
  4.   userAttributes: {             // Optional — all keys and values must be strings
  5.     DeviceType: 'Phone',
  6.     OS: 'Android',
  7.     OSVersion: '14',
  8.     DeviceModel: 'Pixel 8 Pro',
  9.   },
  10. };
Field
Type
Required
Description
userId
string
Yes
Unique identifier for the user. Must be a non-empty string.
userAttributes
object
No
Key-value pairs used for audience targeting. All keys and values must be strings. If omitted, defaults to an empty object.
   





We’ve designed this documentation to guide you every step of the way. If you need further assistance or have any questions, don’t hesitate to contact us at support@zohopagesense.com - we’re always here to help!