React SDK Readme

This SDK enables easy communication with Engine API and can be used by any application which is built using React frameworks.

The SDK consists of three packages:

  • React Native: For applications using the React Native framework
  • Web: For applications written in React JavaScript
  • Common: Methods and constants shared between the other two packages

Installation

  1. Set the default Artifactory npm registry using the following command:
    npm config set @kibo-personalization-js-sdk:registry https://monetate.jfrog.io/artifactory/api/npm/kibo-npm-local
  2. Install the desired SDK packages using the following commands:
    • React Native
      npm install @kibo-personalization-js-sdk/common
      npm install @kibo-personalization-js-sdk/react-native
    • Web
      npm install @kibo-personalization-js-sdk/common
      npm install @kibo-personalization-js-sdk/Web

Using the SDK

Below are the details about methods and classes with their description and usage.

Kibo Personalization Class

KiboPersonalization is the main class, and creates the object used for all SDK activities. Import it using the following code:

import KiboPersonalization from '@kibo-personalization-js-sdk/react-native';

You can create an instance of this class using the following code:

const KiboPersonalizationInstance = KiboPersonalization (
  account,
  user,
  contextMap?
)

account and user are required parameters, and contextMap is an optional parameter.

Account Object

This object contains information about the account.

export const account = {
  domain: '', // Domain name
  name: '', // Account name
  instance: '', // Instance for the domain
  shortname: '', // Short name for the account
};

You must provide data for these variables.

User Object

This object contains information about the user.

export const user = {
  deviceId: '', // Device ID
  kiboId: '', // Kibo ID
  customerId: '', // Customer ID.
  preview: '', // Preview
  channel: '', // Channel name in this format: { account.name/account.instance/account.domain }
};

Considerations for this object:

  • If deviceId has a value it should be the default ID sent in all calls.
  • You can set the kiboId parameter to auto. If kiboId is auto, the SDK generates a new ID to replace this parameter with the returned ID. kiboId can also be a value set by the client. If deviceId is not defined, then use kiboId as the default ID.
  • The value from auto is populated into key/value pairs, and can be read later if you want to save this data.
  • Either kiboId or deviceId is required in calls. You cannot pass both together in a call.
  • If customerId is defined, you must also pass it in all calls along with one of the other IDs. Do not change this ID after initialization outside of calling the setCustomerId method.

Context Map Object

This object contains optional contextual data such as app/page data layer, state, or other variables.

export const contextMap = {
  coordinates: 'auto',
  screenSize: 'auto',
  ipAddress:'auto',
  userAgent:'auto',
  Cart: ...,
  PageView: ...
};

These variables can be mapped to other variables or functions. All variables other than Cart and PageView can be set to auto.

Methods

The following methods are available to use.

Report

This method is used to report events. Pass the event type as context and the event data as eventData.

KiboPersonalization.report(context, eventData)

The Common package includes various event types as part of the EventTypes object that you can import for the purposes of this method. The naming convention of events for this is EventType.<event name>, where <event name> is the name of the event to pass. The complete list of event names available to use is listed in the Common Package Constants and Interfaces section.

Example:

const cart = {
  "cartLines": [{
    "sku": "SKU1",
    "pid": "PID1",
    "quantity": 2,
    "currency": "USD",
    "value": "24.00"
  }] 
};
kiboPersonalizationInstance.report(
  EventTypes.ContextCart, 
  { cartLines: cart }
);

Get Action

This method is used to record events and request decisions.

KiboPersonalization.getActions(requestId, context?, eventData?)

Parameters:

  • requestId is the request identifier tying the response back to an event.
  • context is the name of the event. This parameter is optional. If you use this parameter, include contextMap data relevant to the requirements for the event.
  • eventData is the data associated with the events. This parameter is optional.

This method returns an object containing the JSON of the event. The status value of this includes a HTTP response code in the following format:

{meta: {code: ###}}

If this method returns a code other than 200, this indicates a failed response and the method does not return any actions.

In order to make use of this method, you must first create an Omnichannel experience. Refer to Create an Omnichannel Experience for information on creating an Omnichannel experience. Use the JSON found at OmniJSON Template for Engine API SDKs as your input.

Example usage:

const App = () => {
  const kiboPersonalizationInstance = KiboPersonalization(account, user, contextData)
  const [actionData, setActionData] = useState({});


  const handleGetActions = () => {
    const requestId = String(Math.random());
    const eventType = EventTypes.ContextCart;
    kiboPersonalizationInstance.getActions(requestId, eventType)
      .then((res) => {
        if (res.length > 0) {
          res[0].actions.map((action) => {
            if (action.json.meta && action.json.meta.tool === 'react-native') {
              const data = {
                color: action.json.data.json.color,
                text: action.json.data.json.text,
                fontSize: action.json.data.json.fontSize,
                style: action.json.data.json.style,
                buttonText: action.json.data.json.buttonText,
                buttonColor: action.json.data.json.buttonColor,
              };
              setActionData(prevState => {
                return {
                  ...prevState,
                  decisionEventData: data,
                }
              });
            } else {
              console.warn('Meta Object not present in Omni JSON.');
            }
          });
        }
      })
      .catch((error) => console.warn('Please try after some time!', error));
  };


  useEffect(() => {
    handleGetActions();
  }, []);


  return <div>Handle Get Actions demo < /div>;
};

Flush

This method sends all queued data immediately. Use this method if you want to report an event immediately.

KiboPersonalization.flush()

This method might throw the following exceptions that you might need to handle:

  • InterruptedException
  • ExecutionException
  • TimeoutException

Example usage:

const kiboPersonalization = new KiboPersonalization(account, user, contextMap);


kiboPersonalizationInstance.report (
  'monetate:context:IpAddress',
  { ipAddress: 10.10.10.10 }
),
kiboPersonalization.setCustomerId("test_customer_id");
kiboPersonalization.flush();

Set Customer ID

This method sets or updates the customerId of the User object.

KiboPersonalization.setCustomerId(customerId)

Example usage:

const kiboPersonalizationInstance = new KiboPersonalization(account, user, contextMap);


kiboPersonalizationInstance.setCustomerId("test_customer_id");

Common Package Constants and Interfaces

The following is a list of resources in the Common package for use in development.

Event Type Constants

You can import event type constants using the following code:

import { EventTypes } from '@kibo-personalization-js-sdk/common';

Event types are then referenced by the name EventTypes.eventName. The available event names are:

  • RecordImpressions
  • RecordPageEvents
  • RecordRecClicks
  • RecordRecImpressions
  • ContextCustomVariables
  • ContextUserAgent
  • ContextPageView
  • ContextProductView
  • ContextCart
  • ContextPurchase
  • ContextMetadata
  • ContextProductDetailView
  • ContextProductThumbnailView
  • ContextReferrer
  • ContextCoordinates
  • ContextScreenSize
  • ContextClosedSession

IP address events are not available in this package. As a workaround, you can use the monetate:context:IpAddress event to report IP addresses. An example of this usage:

kiboPersonalizationInstance.report(
  'monetate:context:IpAddress', { ipAddress: 10.10.10.10 }
)

Auto Trackable Events

Auto trackable events are events where you can pass auto as the contextMap parameter to automatically gather required details for reporting.

The following events are auto trackable:

ContextConstantsString in contextMap and context
monetate:context:ReferrerContextReferrerReferrer
monetate:context:CoordinatesContextCoordinatesCoordinates
monetate:context:ScreenSizeContextScreenSizeScreenSize

Referrer is available only in the Web SDK package.

Example usage:

import KiboPersonalization from '@kibo-personalization-js-sdk/react-native';
// For web-based applications import '@kibo-personalization-js-sdk/web'
import { EventTypes } from '@kibo-personalization-js-sdk/common';
const kiboPersonalizationInstance = new KiboPersonalization(account, user, contextMap);


kiboPersonalizationInstance.report(
  // Screen Size Event 
  kiboPersonalizationInstance.report(
    EventTypes.ContextScreenSize,
    'auto')
)

Events

Refer to React Web Event Code Samples and React Native Event Code Samples for a list of events and code samples you can use.