React-Native SDK

Overview

This guide provides detailed instructions on integrating the React Native algonomy wrapper with a React Native application. The wrapper acts as a bridge to Algonomy's TargetOne Mobile SDK, allowing developers to send clickstream events and configure customer profiles in real-time.

This integration is critical for retailers and marketers who leverage Algonomy's Real-time Customer Data Platform (CDP) to deliver personalized customer experience based on behavioral data and user profiles collected from mobile apps.

Installation

To begin, install the Algonomy React Native wrapper via npm.

  1. Open your terminal

  2. Run the following command to add the wrapper to your project:

    Copy
    < npm install react-native-algonomy >

    This command installs the Algonomy wrapper library, enabling JavaScript-level access to Algonomy’s SDK functionalities

  3. Create a module to communicate with native functionality in AlgonomyModule.java

    Copy
    import android.app.Activity;
    import android.content.Context;
    import android.util.Log;

    import androidx.annotation.NonNull;

    import com.facebook.react.bridge.Callback;
    import com.facebook.react.bridge.ReactApplicationContext;
    import com.facebook.react.bridge.ReactContextBaseJavaModule;
    import com.facebook.react.bridge.ReadableMap;
    import com.facebook.react.bridge.ReactMethod;
    import com.facebook.react.module.annotations.ReactModule;
    import com.manthan.targetone.Interface.APIResponseInterface;
    import com.manthan.targetone.Model.Customer;
    import com.manthan.targetone.TargetOneMobileSDK;

    import org.json.JSONObject;

    /**
     * React Native module that provides integration with the Algonomy TargetOneMobileSDK.
     * This module allows for sending clickstream data, real-time API events, and setting customer profiles.
     */
    @ReactModule(name = AlgonomyModule.NAME)
    public class AlgonomyModule extends ReactContextBaseJavaModule {

        public static final String NAME = "AlgonomyModule";

        private final Context context;
        private final Activity activity;
        private static final TargetOneMobileSDK instance = TargetOneMobileSDK.getInstance();
        private Callback callback1;

        /**
         * Constructor for the AlgonomyModule.
         *
         * @param context The ReactApplicationContext used to initialize the module.
         */
        public AlgonomyModule(ReactApplicationContext context) {
            super(context);
            this.context = context;
            this.activity = getCurrentActivity();
        }

        /**
         * Sends a clickstream event to the TargetOneMobileSDK.
         *
         * @param eventType The type of the event being tracked.
         * @param eventData The data associated with the event.
         * @param callback  The callback to handle the response.
         */
        @ReactMethod
        public void sendClickStream(String eventType, ReadableMap eventData, Callback callback) {
            try {
                Log.v("T1", "send: Click Event Type:" + eventType);
                Log.v("data", eventData.toString());

                callback1 = callback;
                final Activity activity = getCurrentActivity();

                activity.runOnUiThread(() -> {
                    instance.sendClickStream(activity, eventType, new JSONObject(eventData.toHashMap()), apiResponseInterface);
                });

            } catch (Exception e) {
                Log.e("Catch Exception", e.getMessage());
                callback.invoke("error");
                throw e;
            }
        }

        /**
         * Sends a real-time API event to the TargetOneMobileSDK.
         *
         * @param eventType The type of the event being tracked.
         * @param ruleName  The name of the rule associated with the event.
         * @param eventData The data associated with the event.
         * @param callback  The callback to handle the response.
         */
        @ReactMethod
        public void sendRealtimeAPI(String eventType, String ruleName, ReadableMap eventData, Callback callback) {
            Log.i("T1", "send: sendRealtimeAPI Event Type: " + eventType + ", data : " + eventData);
            callback1 = callback;
            final Activity activity = getCurrentActivity();

            activity.runOnUiThread(() -> {
                instance.sendRealtimeAPI(activity, eventType, ruleName, new JSONObject(eventData.toHashMap()), apiResponseInterface);
            });
        }

        /**
         * Sets the customer profile in the TargetOneMobileSDK.
         *
         * @param customer The customer profile data.
         */
        @ReactMethod
        public void setCustomerProfile(ReadableMap customer) {
            Log.i("T1", "Set Customer Profile: " + customer);

            Customer customerObj = new Customer();
            customerObj.setEmail(customer.getString("email"));
            customerObj.setMobileNo(customer.getString("mobileNo"));
            customerObj.setCustomerCode(customer.getString("customerCode"));

            final Activity activity = getCurrentActivity();
            activity.runOnUiThread(() -> {
                instance.setCustomerProfile(activity, customerObj);
            });
        }

        @Override
        @NonNull
        public String getName() {
            return NAME;
        }

        // API response handler
        private final APIResponseInterface apiResponseInterface = (statusCode, jsonObject, s) -> {
            Log.i("APIRESPONSE", "DATA");
            Log.i("StatusCode", String.valueOf(statusCode));
            Log.i("S", s);
            callback1.invoke(statusCode, jsonObject, s);
        };
    }

JavaScript Integration

After installation, you can import and use the wrapper in your JavaScript or TypeScript files to interact with Algonomy's SDK.

Import the wrapper module in your JS code:

Copy
< import Algonomy from 'react-native-algonomy >
Example usage:
// Set customer profile
Algonomy.setCustomerProfile({
  email: 'user@example.com',
  mobileNo: '9876543210',
  customerCode: 'CUST123'
});

// Send click stream event
Algonomy.sendClickStream('eventProduct', { productId: 'P001' }, (statusCode, data, message) => {
  console.log('Event response:', statusCode, data, message);
});

The above example helps you to set the customer profile using set Customer Profile, which registers user details like email, mobile number, and customer code. It also sends a clickstream event using send ClickStream, which logs a user interaction (e.g., viewing a product) and returns a response via a callback.

Native Setup

To enable full functionality of the wrapper, you must configure platform-specific native modules for both Android and iOS. This setup ensures that the React Native layer can communicate with Algonomy’s TargetOne SDK through the respective native environments.

Android

To integrate the native Android module:

  1. File: AlgonomyModule.java

  2. Ensure the following Java module is included in your Android codebase at the following path:

  3. Copy
    android/app/src/main/java/...
    File: RTCAlgonomyModule.m

iOS (Objective-C)

Ensure that the Objective-C implementation is added to your project and properly linked in Xcode. This module uses TargetOne’s shared instance to communicate with the SDK.

iOS (Swift)

If your app uses Swift, you can create a Swift version of the module. Make sure that:

  • A bridging header is present.

  • The module confirms to the RCT Bridge Module protocol.

Notes

Keep the following key considerations in mind to ensure smooth and stable integration across platforms:

  • Ensure that the TargetOne SDK is correctly configured for both Android and iOS platforms.

  • For iOS, handle permission prompts and configure required entitlements.

  • Always test the integration thoroughly on real devices for both platforms.

Native Module Implementations

This section provides the native code required to implement the Algonomy React Native module on both Android and iOS platforms. These modules bridge the JavaScript interface with the underlying TargetOne Mobile SDK.

Algonomy Module.java (Android)

This Java class defines the Android-native module for Algonomy integration.

Copy
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import com.manthan.targetone.Interface.APIResponseInterface;
import com.manthan.targetone.Model.Customer;
import com.manthan.targetone.TargetOneMobileSDK;
import org.json.JSONObject;

@ReactModule(name = AlgonomyModule.NAME)
public class AlgonomyModule extends ReactContextBaseJavaModule {

    public static final String NAME = "AlgonomyModule";
    private final Context context;
    private final Activity activity;
    private static final TargetOneMobileSDK instance = TargetOneMobileSDK.getInstance();
    private Callback callback1;


    public AlgonomyModule(ReactApplicationContext context) {
        super(context);
        this.context = context;
        this.activity = getCurrentActivity();
    }

    @ReactMethod
    public void sendClickStream(String eventType, ReadableMap eventData, Callback callback) {
        try {
            Log.v("T1", "send: Click Event Type:" + eventType);
            Log.v("data", eventData.toString());
            callback1 = callback;
            final Activity activity = getCurrentActivity();
            activity.runOnUiThread(() -> {
                instance.sendClickStream(activity, eventType, new JSONObject(eventData.toHashMap()), apiResponseInterface);
            });
        } catch (Exception e) {
            Log.e("Catch Exception", e.getMessage());
            callback.invoke("error");
            throw e;
        }
    }
 @ReactMethod
    public void setCustomerProfile(ReadableMap customer) {
        Log.i("T1", "Set Customer Profile: " + customer);
        Customer customerObj = new Customer();
        customerObj.setEmail(customer.getString("email"));
        customerObj.setMobileNo(customer.getString("mobileNo"));
        customerObj.setCustomerCode(customer.getString("customerCode"));
        final Activity activity = getCurrentActivity();
        activity.runOnUiThread(() -> {
            instance.setCustomerProfile(activity, customerObj);
        });
    }
    @Override
    @NonNull
    public String getName() {
        return NAME;
    }
    private final APIResponseInterface apiResponseInterface = (statusCode, jsonObject, s) -> {
        Log.i("APIRESPONSE", "DATA");
        Log.i("StatusCode", String.valueOf(statusCode));
        Log.i("S", s);
        callback1.invoke(statusCode, jsonObject, s);
    };
}

Register in MainApplication.java

To use the custom native module in your Android app, you must register it in MainApplication.java. This allows the React Native runtime to recognize and load the module at runtime.

  1. File: android/app/src/main/java/.../MainApplication.java

  2. Import the AlgonomyPackage at the top of the file:

  3. Copy
    import com.reactnativealgonomy.AlgonomyPackage; 
  4. Register the package to the list of React packages inside the getPackages() method:

    Copy
    @Override
    protected List<ReactPackage> getPackages() {
        @SuppressWarnings("UnnecessaryLocalVariable")
        List<ReactPackage> packages = new PackageList(this).getPackages();
     // Register the custom native module
        packages.add(new AlgonomyPackage());
       return packages;
    }                                                                           

AlgonomyModule.h/.m (iOS Objective-C)

This Objective-C implementation defines the native module for iOS apps using Objective-C. It exposes methods to set customer profiles and send clickstream events through TargetOne.

Copy
#import "RTCAlgonomyModule.h"
#import <React/RCTLog.h>

@implementation AlgonomyModule

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(setCustomerProfile:(NSDictionary *)customer )
{
  RCTLogInfo(@"Pretending to create an event %@", customer);
  NSString *custCode = [customer objectForKey:@"customerCode"];
  NSString *emailId = [customer objectForKey:@"email"];
  NSString *mobileNumber = [customer objectForKey:@"mobile"];
  T1CustomerProfile *profile = [T1CustomerProfile new];
  profile.custCode =custCode;
  profile.emailId = emailId;
  profile.mobileNumber=mobileNumber;
  [[TargetOne sharedInstance] setCustomerProfile:profile];
}
RCT_EXPORT_METHOD(sendClickStream:(NSString *)eventType eventData:(NSDictionary *)eventData callback:RCTResponseSenderBlock )
{
  NSLog(@"Event Type %@",eventType);
  [[TargetOne sharedInstance] sendClickStream:eventType withProps:eventData];
}

AlgonomyModule.swift (iOS - Swift)

This Swift implementation provides the same functionality as the Objective-C version but is written for iOS apps using Swift. It defines two exposed methods: one to set customer profile data and another to send clickstream events.

Copy
@objc(AlgonomyModule)
class AlgonomyModule: NSObject  
{
@objc(setCustomerProfile:)
  func setCustomerProfile(_ customer: NSDictionary) {
    print("Customer Profile: \(customer)")
    let profile = T1CustomerProfile()
    profile.custCode = customer["customerCode"] as? String ?? ""
    profile.emailId = customer["email"] as? String ?? ""
    profile.mobileNumber = customer["mobile"] as? String ?? ""
    TargetOne.sharedInstance()?.setCustomerProfile(profile)
  }
 @objc(sendClickStream:eventData:callback:)
  func sendClickStream(_ eventType: String, eventData: NSDictionary, callback: RCTResponseSenderBlock?) {
    print("Event Type: \(eventType)")
    TargetOne.sharedInstance()?.sendClickStream(eventType, withProps: eventData as! [AnyHashable : Any])
    callback?([NSNull(), "Event sent"])
  }
}