---
title: Create a Recommendations Action
slug: sdks/recs
description: How to create an Omnichannel Product Recommendations action in the React Web, React Native, iOS, and Android versions of the Monetate SDK
image:  https://archbee-image-uploads.s3.amazonaws.com/ceIfEvQHzQk1IVxoRWUh7/K9eTL4jKm7UQINb6zNziJ-20250912-181225.png
docTags: 
createdAt: 2024-06-13T19:04:38.772Z
---

:::BlockQuote
**Note :**&#x54;his legacy flow remains supported for backward compatibility.New integrations are recommended to use the Context Layer–based getActions() approach. [check below](https://developer.monetate.com/sdks/recs#0Et38)
:::

Omnichannel recommendations is an integrated [product recommendations](https://docs.monetate.com/docs/recommendations) experience that is consistent across all platforms that you connect to Monetate. Whether a customer is viewing your storefront through a mobile app or your site, Omnichannel recommendations ensure a consistent experience.

You can set up a handler for an Omnichannel recommendations action by using two methods. The `addEvents` method defines the events that can trigger the action. The `getActionsData` method is then used as the trigger and requests the decision based on the defined events. `getActionsData` then returns a JSON object containing recommendations data that you can then handle in code.



## Prerequisites

You must first create an Omnichannel experience in the Monetate platform for the methods to reference. Refer to [Configure an Omnichannel Recommendations Action](https://docs.monetate.com/docs/configure-an-omnichannel-recommendations-action) in the Monetate Knowledge Base for instructions.

Make note of the [WHO settings](docId\:uI0Or7GoerH9r_wUMbc6m) because they correspond to events your code listens for. The example experience in this article uses the following WHO settings:

- IP address is 1.0.0.2
- Screen height is at least 500 pixels and screen width is at least 300 pixels

The example code in this article fulfills these conditions and will trigger the Omnichannel experience.

## addEvent.&#x20;

This method adds event data to the SDK's internal stack.

:::::Tabs
::::Tab{title="React Native"}
:::CodeblockTabs
addEvent Method

```javascript
addEvent(context: EventTypes, events: ContextData): void
```
:::

The parameters are as follows:

- `context` is name of the event.
- `events` is the event data.
::::

::::Tab{title="React Web"}
:::CodeblockTabs
addEvent Method

```javascript
addEvent(context: EventTypes, events: ContextData): void
```
:::

The parameters are as follows:

- `context` is name of the event.
- `events` is the event data.
::::

::::Tab{title="iOS"}
:::CodeblockTabs
addEvent Method

```swift
addEvent(context: <ContextEnum>, event: <MEvent?>)
```
:::

The parameters are as follows:

- `context` is name of the event. (Required)
- `event` is the event data. (Required)
::::

::::Tab{title="Android"}
:::CodeblockTabs
addEvent Method

```java
public void addEvent(String context, Object event)
```
:::

The parameters are as follows:

- `context` is name of the event. (Required)
- `event` is the event data. (Required)
::::
:::::

You can use this method multiple times to add all the necessary events for an experience you might want to trigger. The example code uses multiple method calls to fulfill the experience requirements.

### Code Example

:::::Tabs
::::Tab{title="React Native"}
:::CodeblockTabs
addEvent Example

```javascript
personalizationInstance.addEvent(EventTypes.ContextScreenSize, { width: 23, height: 34 });

personalizationInstance.addEvent(EventTypes.ContextIpAddress, {
  ipAddress: "10.0.0.2",
});

personalizationInstance.addEvent(EventTypes.ContextPageView, {
  url: "http://www.monetate.com/index.html",
  pageType: "Home"
});
```
:::
::::

::::Tab{title="React Web"}
:::CodeblockTabs
addEvent Example

```javascript
personalizationInstance.addEvent(EventTypes.ContextScreenSize, { width: 23, height: 34 });

personalizationInstance.addEvent(EventTypes.ContextIpAddress, {
  ipAddress: "10.0.0.2",
});

personalizationInstance.addEvent(EventTypes.ContextPageView, {
  url: "http://www.monetate.com/index.html",
  pageType: "Home"
});
```
:::
::::

::::Tab{title="iOS"}
:::CodeblockTabs
addEvent Example

```swift
objPersonalization.addEvent(context: .ScreenSize, event: ScreenSize(height: 1000, width: 400))

objPersonalization.addEvent(context: .IpAddress, event: IPAddress(ipAddress: "192.168.1.52")) 

objPersonalization.addEvent(context: .PageView, event: PageView(pageType: "PDP", path: "n/a", url: "n/a", categories: [], breadcrumbs: [])) 
```
:::
::::

::::Tab{title="Android"}
:::CodeblockTabs
addEvent Example

```java
personalization.addEvent(EventTypes.ContextIpAddress, new IpAddress("1.0.0.0"));
personalization.addEvent(EventTypes.ContextPageView, new PageView("home", "test.com",new String[] {"categoies"} ,new String[] {"breadcrums"}));
personalization.addEvent(EventTypes.ContextScreenSize, new ScreenSize(1011, 2011));
```
:::
::::
:::::

## getActionsData

This method sends the defined events to Monetate to trigger an experience. If the events fulfill the WHO settings of an experience, then that experience is triggered. A JSON object containing the experience response is then returned.

:::::Tabs
::::Tab{title="React Native"}
:::CodeblockTabs
getActionsData Method

```javascript
getActionsData(actionType: Array<string>, includeReporting?: boolean) : Promise<any>
```
:::

The parameter is as follows:

- `actionType` is the type of action you want to request. You can specify one action or multiple actions in an array to handle.
- `includeReporting` indicates whether the response will have impression reporting data.
::::

::::Tab{title="React Web"}
:::CodeblockTabs
getActionsData Method

```javascript
getActionsData(actionType: Array<string>, includeReporting?: boolean) : Promise<any>
```
:::

The parameter is as follows:

- `actionType` is the type of action you want to request. You can specify one action or multiple actions in an array to handle.
- `includeReporting` indicates whether the response will have impression reporting data.
::::

::::Tab{title="iOS"}
:::CodeblockTabs
getActionsData Method

```swift
getActionsData(requestId: <String>, includeReporting: <Bool>, arrActionTypes: <[String]>) 
```
:::

The parameters are as follows:

- `requestID` is the request ID for the API.
- `includeReporting` indicates whether the response will have impression reporting data.
- `arrActionTypes` is the type of action you want to request. You can specify one action or multiple actions in an array to handle.
::::

::::Tab{title="Android"}
:::CodeblockTabs
getActionsData Method

```java
public String getActionsData(String[] actionTypes, boolean includeReports)
```
:::

The parameters are as follows:

- `actionTypes` is the type of action you want to request. You can specify one action or multiple actions in an array to handle.
- `includeReports` indicates whether the response will have impression reporting data.
::::
:::::

### Code Example

:::::Tabs
::::Tab{title="React Native"}
:::CodeblockTabs
getActionsData Example

```javascript
let recData;
personalizationInstance
  .getActionsData("monetate:action:OmnichannelRecommendation")
  .then(res => {
    recsData = res[0].actions;
  })
  .catch(error => {
    console.warn('Error!', error);
  });
```
:::
::::

::::Tab{title="React Web"}
:::CodeblockTabs
getActionsData Example

```javascript
let recData;
personalizationInstance
  .getActionsData("monetate:action:OmnichannelRecommendation")
  .then(res => {
    recsData = res[0].actions;
  })
  .catch(error => {
    console.warn('Error!', error);
  });
```
:::
::::

::::Tab{title="iOS"}
:::CodeblockTabs
getActionsData Example

```swift
objPersonalization.getActionsData(requestId: "123456", includeReporting: false, arrActionTypes:["monetate:action:OmniChannelRecommendation"]).on{res in 
  if res.status==200 {
    self.handleRecommendations(res: res)
  } else {
  }
 }
}
```
:::
::::

::::Tab{title="Android"}
:::CodeblockTabs
getActionsData Example

```java
String responseData = personalization.getActionsData(new String[]{"monetate:action:OmnichannelRecommendation"},true);
```
:::
::::
:::::

## Full Code Example

:::::Tabs
::::Tab{title="React Native"}
:::CodeblockTabs
Recommendations Action Full Example

```javascript
// Add Context / Events
// -----------------------------------------------------
personalizationInstance.addEvent(EventTypes.ContextScreenSize,
{
  width: 23,
  height: 34
});
personalizationInstance.addEvent(EventTypes.ContextIpAddress,
{
  ipAddress: "10.0.0.2",
});
personalizationInstance.addEvent(EventTypes.ContextPageView,
{
  url: "http://www.monetate.com/index.html",
  pageType: "Home"
});
// ----------------------------------------------------
// Get Actions
let recData;
personalizationInstance
  .getActionsData("monetate:action:OmnichannelRecommendation")
  .then(res =>
  {
    recsData = res[0].actions;
  })
  .catch(error =>
  {
    console.warn('Error!', error);
  });
```
:::
::::

::::Tab{title="React Web"}
:::CodeblockTabs
Recommendations Action Full Example

```javascript
// Add Context / Events
//-------------------------------------------------------------------------
personalizationInstance.addEvent(EventTypes.ContextScreenSize, { width: 23, height: 34 });

personalizationInstance.addEvent(EventTypes.ContextIpAddress, {
  ipAddress: "10.0.0.2",
});

personalizationInstance.addEvent(EventTypes.ContextPageView, {
  url: "http://www.monetate.com/index.html",
  pageType: "Home"
});

// Get Actions
// ----------------------------------------------------
let recData;
personalizationInstance
  .getActionsData("monetate:action:OmnichannelRecommendation")
  .then(res => {
    recsData = res[0].actions;
  })
  .catch(error => {
    console.warn('Error!', error);
  });
```
:::
::::

::::Tab{title="iOS"}
:::CodeblockTabs
Recommendations Action Full Example

```swift
// Add Context / Events
//-------------------------------------------------------------------------
objPersonalization.addEvent(context: .ScreenSize, event: ScreenSize(height: 1000, width: 400))

objPersonalization.addEvent(context: .IpAddress, event: IPAddress(ipAddress: "192.168.1.52"))

objPersonalization.addEvent(
  context: .PageView,
  event: PageView(pageType: "PDP", path: "n/a", url: "n/a", categories: [], breadcrumbs: []))

// Get Actions
// ----------------------------------------------------
objPersonalization.getActionsData(
  requestId: "123456", 
  includeReporting: false,
  arrActionTypes: ["monetate:action:OmnichannelRecommendation"]
).on { res in
  if res.status == 200 {
    self.handleRecommendations(res: res)
  } else {
  }
}

private func handleRecommendations(res: APIResponse) {
  let data = JSON(res.data as Any)
  for item in data["data"]["responses"].arrayValue {
    if item["requestId"].string == res.requestId {
      for oneAction in item["actions"].arrayValue {
        if oneAction["component"].string == "iOS_InApp_Recs" {
          recProductArr.removeAll()
          self.recLabel.isHidden = false
          self.recLineSeperatorView.isHidden = false
          self.collectionView.isHidden = false

          for productDict in oneAction["items"].arrayValue {
            for cat in CategoryGeneratorforProducts.categories {
              for prdct in cat.products {
                if prdct.pid == productDict["id"].rawValue as! String {
                  prdct.recToken = productDict["recToken"].rawValue as? String
                  prdct.recSetId = productDict["recSetId"].rawValue as? Double
                  prdct.affinity = productDict["_affinity"].rawValue as? Double
                  prdct.rawAffinity = productDict["_rawAffinity"].rawValue as? Double
                  prdct.slotIndex = productDict["slotIndex"].rawValue as? Int
                  recProductArr.append(prdct)
                }
              }
            }
          }
          self.collectionView.reloadData()
          DispatchQueue.main.asyncAfter(
            deadline: .now() + 2.0,
            execute: {
              self.collectionView.reloadData()
            })
          return
        }
      }
    }
  }
}
```
:::
::::

::::Tab{title="Android"}
:::CodeblockTabs
Recommendations Action Full Example

```java
Personalization personalization = new personalization(user, account);

// Events and context data
IpAddress ipAddress = new IpAddress();
ipAddress.setIpAddress("1.0.0.0");
ScreenSize screenSize = new ScreenSize();
screenSize.setHeight(1011);
screenSize.setWidth(2011);
PageView pageView = new PageView();
pageView.setPageType("Cartpage");
pageView.setUrl("https://www.monetate.com");

// addEvent
personalization.addEvent(EventTypes.ContextScreenSize, screenSize);
personalization.addEvent(EventTypes.ContextIpAddress, ipAddress);
personalization.addEvent(EventTypes.ContextPageView, pageView);

// getActionsData
String responseData;
new Thread(new Runnable()
{
  @Override
  public void run()
  {
    // Gets the responseData using getActionsData
    responseData = personalization.getActionsData(new String[]
    {
      "monetate:action:OmnichannelRecommendation"
    }, true);
    // Once you receive the responseData from getActionsData, use the Handlerand parse the required data from it 
    new Handler(Looper.getMainLooper()).post(new Runnable()
    {
      @Override
      public void run()
      {
        // Parse the received responseData, get the requiredData from it and use it accordingly
        try
        {
          // Example: textView.setText(requiredData);
        }
        catch (Exception ex)
        {
          // Catch any exception that occurs while parsing 
          ex.printStackTrace();
        }
      }
    });
  }
}).start();
```
:::

You must handle the `getActions` method in a `Thread` or `AsyncTask`. To update the main thread, you can use either `Handler` or `runOnUiThread`. This full code example uses `Thread` and `Handler` to update the main thread and change the UI.



## Recommendations using Context Layer&#x20;

:::BlockQuote
**Note:**&#x54;he Context-based getActions() flow replaces the need to manually use addEvent and getActionsData when evaluating actions.
:::

<font color="#15803D">**Supported SDK Versions**</font>

- <font color="#4283c7">**Android**</font>: 1.0.6-A or later&#x20;
- <font color="#4283c7">**React-Native**</font>: 1.0.6-RN or later&#x20;
- <font color="#4283c7">**Web**</font>: 1.0.6-W or later&#x20;
- <font color="#4283c7">**iOS**</font>**:** 2026.01.06 or later

Using the new **Context Layer–based approach**, Recommendation Actions can be implemented using a single enhanced **getActions()&#x20;**&#x6D;ethod. Below is the sample code snippet demonstrating this usage.

For detailed information on the enhanced getActions() flow, please refer to the [Context](https://developer.monetate.com/sdks/objects#mDSKQ) and [getActions](https://developer.monetate.com/sdks/getactions) sections.



## Code Exmaple
::::
:::::

:::::Tabs
::::Tab{title="iOS"}
:::CodeblockTabs
getActions() method

```swift
public func getActions(context:ContextObj, arrActionTypes:[String], includeReporting: Bool)
```
:::
::::

::::Tab{title="Android"}
:::CodeblockTabs
getActions() method

```java
public void getActions(Context context, String[] actionTypes, boolean includeReports, ActionsCallback actionsCallback);
```
:::
::::

::::Tab{title="React-Native"}
:::CodeblockTabs{indent="2"}
getAction Method RN

```typescript
 async getActions(
        actionType: string | string[],
        context?: any,
        includeReporting: boolean = true,
        errorCallback?: (result: { status: "success" | "failed"; error?: unknown }) => void
    ): Promise<{ data: unknown; errors?: unknown }> {}

```
:::
::::

::::Tab{title="Web"}
:::CodeblockTabs{indent="2"}
getAction Method Web

```typescript
 async getActions(
        actionType: string | string[],
        context?: any,
        includeReporting: boolean = true,
        errorCallback?: (result: { status: "success" | "failed"; error?: unknown }) => void
    ): Promise<{ data: unknown; errors?: unknown }> {}

```
:::
::::
:::::

## Full code Exmaple

:::::Tabs
::::Tab{title="iOS"}
:::CodeblockTabs
Recommendations Action Full Example

```swift
        //setting up context data
        let contextObj = ContextObj()
        contextObj.addIpAddress("1.0.0.0")
        contextObj.addPageDetails(pageType: "PDP", path: "n/a", url: "n/a", categories: [], breadcrumbs: [])
        contextObj.addScreenSizeData(screenHeight: 1000, screenWidth: 400)
        
       //Request Recommendation Action data
        objPersonalization.getActions(context: contextObj, arrActionTypes: ["monetate:action:OmnichannelRecommendation"], includeReporting: false)
            .on(success: { (actions) in
                    self.handleRecommendations(actions: actions)
            })
    }
```
:::
::::

::::Tab{title="Android"}
:::CodeblockTabs{indent="2"}
Recommendations Action Full Example

```java
//setting up context data       
Context context = new Context();
context.addIpAddress("1.0.0.0");
context.addScreenSizeData(1010, 2121);
context.addPageDetails("homepage", "https://www.monetate.com", new String[] {"categories-here"},new String[] {"breadcrums--here"},"test/path");

//Request Recommendation Action data		
personalization.getActions(context, new String[] {"monetate:action:OmnichannelRecommendation"}, false,new ActionsCallback() {	
	@Override
	public void onSuccess(String actions) {
	    // print the action data received here 
		System.out.println("Action data :"+actions);		
	}
	@Override
	public void onError(Exception e) {
		// prints the error/exception data received here 
		System.out.println("Ex :"+e);		
	}
});
```
:::




::::

::::Tab{title="React-Native"}
:::CodeblockTabs{indent="2"}
getAction Method RN

```typescript
const context = new Context();
context
    .addPageDetails()
    .url("www.monetate.com")
    .path(monetate.com)
    .pageType("home")
    .breadcrumbs(["Home"])
    .categories(["Homepage"]);
    
Personalization.getActions(
  ["monetate:action:OmnichannelRecommendation"], 
  context)
  .then((res: any) => console.log("Action [res]", res));
```
:::
::::

:::Tab{title="Web"}

:::
:::::







