# React Native SDK reference

> @releva-ai/sdk-react-native at a glance: client constructor and configuration presets, identity, tracking, push, inbox and on-screen methods, the push payload and tap action, the events each call writes, and the errors to expect.

Reference for `@releva-ai/sdk-react-native` 0.4.x. Setup walkthroughs: [Connect your React Native app](https://releva.ai/documentation/integrations/react-native/connect-your-react-native-app/) and [Push notifications with Expo](https://releva.ai/documentation/integrations/react-native/push-notifications-with-expo/).

## Client

```plaintext
import { RelevaClient, RelevaConfigPresets } from '@releva-ai/sdk-react-native';
const client = new RelevaClient(realm, accessToken, config?);
```

| Argument      | Value                                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `realm`       | `''` for `https://releva.ai`. A non-empty value becomes `https://<realm>.releva.ai`.                                                       |
| `accessToken` | The shop’s **Access Token** from **Settings › Shop & Integration › General**. Sent as `authorization: Bearer <accessToken>` on every call. |
| `config`      | A `RelevaConfig`; default `RelevaConfigPresets.full()`.                                                                                    |

### Configuration

| Preset             | tracking | screen tracking | in-app messaging (banners, stories) | push | analytics | inbox |
| ------------------ | -------- | --------------- | ----------------------------------- | ---- | --------- | ----- |
| `full()` (default) | on       | on              | on                                  | on   | on        | on    |
| `messagingOnly()`  | off      | off             | on                                  | off  | off       | on    |
| `trackingOnly()`   | on       | on              | off                                 | off  | on        | off   |
| `pushOnly()`       | off      | off             | off                                 | on   | off       | off   |

Spread a preset and override single flags or the request settings:

```plaintext
new RelevaClient('', '<yourAccessToken>', {
  ...RelevaConfigPresets.full(),
  requestTimeoutMs: 30000,        // default
  maxRetryAttempts: 3,            // default: 4 attempts in total
  transportRetryDelayMs: 1000,    // default
  serverErrorRetryDelayMs: 2000,  // default
  enableRequestLogging: true,     // default: one log line per request with status and duration
});
```

Every request (tracking, banner and story events, push token, NPS, inbox) is aborted after `requestTimeoutMs` and retried on a transport failure or a 5xx, never on a 4xx. With `enableTracking` off, the `track*` methods return an empty response without a request.

| Method                             | What it does                                                                                                 |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `setEndpointOverride(url \| null)` | Send everything to another base URL (local development). Warns when the URL is not `https://`.               |
| `setAppVersion(version)`           | Reported in the device context; lets NPS surveys target by app version.                                      |
| `dispose()`                        | Stops the session, NPS, inbox and engagement timers and listeners. Call it when the root component unmounts. |

## Identity

| Method                                | What it does                                                                                                                                               |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setDeviceId(id)`                     | Required before any other call; otherwise every call throws `Please provide deviceId before using the client!`. Use a stable id per install.               |
| `setProfileId(id, skipMerge = false)` | Your customer id. The previous id is sent as `mergeProfileIds` on the next push so the anonymous history is merged, unless `skipMerge` is `true` (logout). |

The SDK sends no e-mail, phone number, name or consent. Send those from your backend: [Profiles API overview](https://releva.ai/documentation/reference/profiles/overview/).

## Tracking

All methods below call `POST /api/v0/push` and resolve to a `RelevaResponse` with `recommenders`, `banners` and `stories` (and the NPS survey, consumed by `NpsOverlayWidget`).

| Method                          | Options                                                                                                               | Event written in Releva                                                                                                                  |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `trackScreenView(options?)`     | `screenToken`, `screenName`, `pageUrl`, `productIds`, `categories`, `filter`, `blocks`, `locale`, `currency`          | **Viewed Page**, only when `screenToken` is a page token of the shop                                                                     |
| `trackProductView(options)`     | `screenToken`, `pageUrl`, `productId`, `customFields`, `categories`, `locale`, `currency`                             | **Viewed Product** (plus **Viewed Page** for the token)                                                                                  |
| `trackSearchView(options)`      | `screenToken`, `pageUrl`, `query`, `resultProductIds`, `filter`, `blocks`, `locale`, `currency`                       | **Search**                                                                                                                               |
| `trackCheckoutSuccess(options)` | `orderedCart` (from `createPaidCart(products, orderId)`), `screenToken`                                               | **Cart Checkout Completed**; the stored cart is cleared afterwards                                                                       |
| `trackCustomEvent(options)`     | `customEvents: CustomEvent[]` (action, products, tags, custom fields), `screenToken`, `pageUrl`, `locale`, `currency` | The custom action you name                                                                                                               |
| `setCart(cart)`                 | `createActiveCart(products)`                                                                                          | Cart events (**Cart Updated**, **Cart Item Added** and the like, derived by Releva from the difference) on a change after the first call |
| `setWishlist(products)`         | `[{ id, custom }]`                                                                                                    | Wishlist events (**Item Added to Wishlist** and the like) on a change after the first call                                               |
| `trackEvent(name)`              | an app event name                                                                                                     | Not sent; evaluated locally to trigger or cancel NPS surveys                                                                             |

`filter` takes `NestedFilter.and([...])` / `.or([...])` of `SimpleFilter` values such as `priceRange`, `brand` and `color`. Custom fields on products use `emptyCustomFields()` or `{ string: [...], numeric: [...], date: [...] }` lists of `{ key, values }`.

A `screenToken` that is not a page token is accepted with `200` and writes nothing. Events from bot user agents are dropped; real apps are not affected.

## Push

| Method                                                          | What it does                                                                                                                                                                                                                                                                                                                                                                                                                          |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `EngagementTrackingService.setNotificationAdapter(adapter)`     | Module top level. `notifeeNotificationAdapter` from `/notifee` or `expoNotificationsAdapter` from `/expo`.                                                                                                                                                                                                                                                                                                                            |
| `EngagementTrackingService.handleBackgroundMessage(data)`       | From the Firebase background handler or the Expo background task. Draws the push on Android; refreshes the inbox for a silent sync.                                                                                                                                                                                                                                                                                                   |
| `EngagementTrackingService.handleForegroundMessage(data)`       | From `onMessage` or `addNotificationReceivedListener`.                                                                                                                                                                                                                                                                                                                                                                                |
| `client.enablePushEngagementTracking({ onNotificationTapped })` | Required for tap tracking and routing. Call after `setDeviceId` and `setProfileId`.                                                                                                                                                                                                                                                                                                                                                   |
| `client.checkInitialNotification()`                             | Once, after the previous call and when navigation is ready. Tracks and routes the tap that launched a closed app; resolves immediately otherwise.                                                                                                                                                                                                                                                                                     |
| `client.registerPushToken(deviceType, token, options?)`         | `POST /api/v0/appPush/tokens`. `deviceType`: `android`, `ios`, `huawei`, `other` (only the first two receive pushes). `options.tokenType` `'fcm'` (default) or `'apns'`, `options.bundleId` (required with `apns`), `options.notificationStyle` `'data'` (default) or `'notification'`. Throws `Backend API error: <status>` on anything but `202`. Never re-registers by itself: wire `onTokenRefresh` and re-register after logout. |
| `isRelevaMessage(data)`                                         | `true` for a Releva push payload. Use it to keep your own handlers from touching Releva pushes.                                                                                                                                                                                                                                                                                                                                       |

### Tap action

`onNotificationTapped` receives a `RelevaNotificationAction`:

| Field        | Value                                                                             |
| ------------ | --------------------------------------------------------------------------------- |
| `target`     | `'screen'`, `'url'`, `'inbox'` or `null` (**Main Screen**)                        |
| `screen`     | The **Screen** name set under **Mobile Targeting** on the push’s **Behavior** tab |
| `url`        | The **URL** target                                                                |
| `parameters` | The **KV Pairs** as an object; for `inbox`, `{ inboxMessageId }`                  |

The SDK records the click (a `GET` of the push’s `callbackUrl`, queued while offline for up to 24 hours, at most 100 pending) before calling you. Releva counts it as **PushNotification Click**.

### Push payload

Releva sends FCM data messages with these keys, which the adapters read: `click_action` (`RELEVA_NOTIFICATION_CLICK`, or `RELEVA_INBOX_SYNC` for a silent sync), `title`, `body`, `imageUrl`, `button`, `target`, `navigate_to_screen`, `navigate_to_url`, `navigate_to_parameters` (a JSON string), `inbox_sync`, `callbackUrl`. Android messages are data-only with `high` priority (`normal` when the notification is **Silent**); iOS messages also carry `aps.alert` and `mutable-content: 1`, so iOS draws them itself in the background. See [What a delivered push contains](https://releva.ai/documentation/reference/push-notifications/overview/#what-a-delivered-push-contains).

## App Inbox

`client.initializeInbox()` after `setProfileId`; then `InboxService.state`, `InboxService.addListener`, `refresh()`, `loadMore()`, `markAsRead(id)`, `markAllAsRead()`, `deleteMessage(id)`, `getMessageById(id)` and the `InboxMessageWidget`. The inbox refreshes on a silent sync push handed to `handleForegroundMessage` or `handleBackgroundMessage`, and on resume when the cache is older than 5 minutes. Details and the endpoints: [How the App Inbox works](https://releva.ai/documentation/learn/inbox/how-the-app-inbox-works/#using-the-sdks), [Inbox API overview](https://releva.ai/documentation/reference/inbox/overview/).

## On-screen content

| Component or service                                                                                             | Purpose                                                                                                                                                                                                                                                                                                   |
| ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BannerDisplayWidget` (`client`, `targetSelector`, `onLinkTap`, children render prop with `header` and `footer`) | Draws popup, flyout, bar and static banners of the screen                                                                                                                                                                                                                                                 |
| `StoryDisplayWidget` (`client`, `onLinkTap`)                                                                     | Draws stories                                                                                                                                                                                                                                                                                             |
| `NpsOverlayWidget` (`onSubmit(token, score, comment)`)                                                           | Draws NPS surveys; call `client.submitNpsResponse({ token, score, comment })` in `onSubmit` (`POST /api/v0/nps/{token}/submissions`)                                                                                                                                                                      |
| `BannerManagerService`, `StoryManagerService`                                                                    | One instance each per app. `initialize(response.banners)` / `initialize(response.stories)` after every screen view; `setScrollOffset(offset, maxOffset)`, `notifyCartChanged()`, `notifyWishlistChanged()` drive the scroll, cart and wishlist triggers. Without `initialize` no banner or story appears. |

Banner impressions go to `POST /api/v0/impressions`, banner and story clicks and closes to `POST /api/v0/push/events`. The leave-intent trigger is web-only.

## Errors

| Where                   | Message                                            | Cause                                                                                                                                                                                                                                                         |
| ----------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SDK, before any request | `Please provide deviceId before using the client!` | `setDeviceId` not called                                                                                                                                                                                                                                      |
| SDK log                 | `[Releva] No notification adapter registered…`     | Adapter not set at module top level                                                                                                                                                                                                                           |
| `registerPushToken`     | `Backend API error: 400`                           | See the backend messages in the [push notifications reference](https://releva.ai/documentation/reference/push-notifications/overview/#register-a-mobile-app-push-token): raw APNs token without `tokenType`, missing `bundleId`, no iOS Firebase account, APNs import rejected |
| Any call                | `Backend API error: 402`                           | The shop is disabled                                                                                                                                                                                                                                          |

## Next steps

* [Mobile SDKs overview](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/): See the four things to set up in the Releva admin for your app.
* [Push notifications API overview](https://releva.ai/documentation/reference/push-notifications/overview/): Register an app push token and see what a delivered push contains.
* [Events API overview](https://releva.ai/documentation/reference/events/overview/): Send custom events and read them back.
* [How product blocks work](https://releva.ai/documentation/learn/product-blocks/how-product-blocks-work/): See how recommendations are chosen and shown in your app.