React Native V2.0.X
Introduction
SDK overview
Welcome to the Flagship React Native SDK documentation!
The following documentation helps you to run Flagship on your React Native environment.
Flagship React Native SDK provides a <FlagshipProvider />
, which makes Flagship features available to the rest of your app.
Flagship features are accessible using Flagship hooks, have a look at the documentation for details.
Feel free to contact us if you have any questions regarding this documentation.
SDK features
This SDK version helps you:
- Set a visitor ID
- Update visitor context
- Assign campaigns via the Decision API or via the Bucketing
- Get modifications
- Keep last received modifications when the phone is offline.
- Activate campaigns
- Send hits to our Universal Collect
Prerequisites
- Node.js: version 6.0.0 or later
- Npm: version 5.2.0 or later
- React: version 16.8.0 or later (the SDK only supports hooks for now)
Good to know
Getting started
Initialization
There are four steps to follow to get started with the React Native Flagship SDK.
- Install the node module
npm install @flagship.io/react-native-sdk
- Import the Flagship React provider
In most cases, do this in yourApp.js
file to wrap your entire app with the provider.
import React from "react";
import { FlagshipProvider } from "@flagship.io/react-native-sdk";
const App = () => (
<>
<FlagshipProvider>{/* [...] */}</FlagshipProvider>
</>
);
- Initialize the provider
You must at least include the required props likeenvId
, apiKey
, visitorData
.
NOTE: apiKey is not required for now but will be in next major release!
import React from "react";
import { FlagshipProvider } from "@flagship.io/react-native-sdk";
const App = () => (
<>
<FlagshipProvider
envId="YOUR_ENV_ID"
apiKey="YOUR_API_KEY" // <= Required in next major release
visitorData={{
id: "YOUR_VISITOR_ID",
context: {
// some context
},
}}
enableConsoleLogs={true}
>
{/* [...] */}
</FlagshipProvider>
</>
);
- Use a Flagship hook in a component
In most case, you will get the desired modifications.
import React from "react";
import { useFsModifications } from "@flagship.io/react-native-sdk";
export const MyReactComponent = () => {
const fsModifications = useFsModifications([
{
key: "backgroundColor",
defaultValue: "green",
activate: false,
},
]);
return (
<View
style={[
{
height: "200px",
width: "200px",
backgroundColor: fsModifications.backgroundColor,
},
]}
>
{"I'm a square with color=" + fsModifications.backgroundColor}
</View>
);
};
API Reference
FlagshipProvider
FlagshipProvider
Here is the full list of props available to use inside the FlagshipProvider
React component:
Props | Type | Default | Description |
---|---|---|---|
envId | string | Required | Your Flagship environment id |
visitorData | object | Required | This is the data to identify the current visitor using your app |
onInitStart | function():void | null | Callback function called when the SDK starts initialization |
onInitDone | function():void | null | Callback function called when the SDK ends initialization |
onUpdate | function(object):void | null | Callback function called when the SDK is updated. For example, after a synchronize is triggered or visitor context has changed |
onBucketingSuccess | function(object):void | null | Callback function called when the bucketing polling succeed |
onBucketingFail | function(object):void | null | Callback function called when the bucketing polling failed |
initialModifications | Array(object) | undefined | This is an array of modifications where each element must be same shape as the element inside the "campaigns" attribute. Providing this prop prevents the SDK from having an empty cache when it first initializes. If the shape of an element is not correct, an error log will give the reason why |
initialBucketing | Array(object) | undefined | This is an object of the data received when fetching bucketing endpoint. |
loadingComponent | React.ReactNode | undefined | This component will be rendered when Flagship is loading at first initialization only. By default, the value is undefined. It means it will display your app and it might display default modifications value for a very short moment. |
fetchNow | boolean | true | Decide to fetch automatically modifications when SDK is initialized. |
activateNow | boolean | false | Enable it to display logs on the console when SDK is running. This will only display logs such as Warnings, Errors, Fatal errors and Info. |
enableSafeMode | boolean | false | Enable it to run the SDK into a safe mode when an error might occurs through the SDK. When safe mode is triggered, default modifications will be returned and other function will just be executed without doing anything. NOTE: This feature is currently catching errors globally (SDK + your app) which might leads to unexpected SDK safe mode if the error comes from your app. We're working on that issue. |
enableErrorLayout | boolean | false | This is a small layout visible at the bottom of the screen. It is displayed only when an unexpected error occurred in the SDK. By default, it's set to false and if set to true , it will be only visible in a node environment other than production |
nodeEnv | string | 'production' | If value is other than production , it will also display Debug logs. |
flagshipApi | string | This setting can be useful if you need to simulate the API for tests such as end-to-end or if you want to move to an earlier version of the Flagship API. Decision API V1 is set by default but deprecated, starting next version, only Decision API V2 will be implemented. | |
decisionMode | 'API' | 'Bucketing' | 'API' | Indicates the behavior of the SDK. |
pollingInterval | number | null | Indicates the polling interval period in seconds when SDK is running Bucketing mode (decisionMode="Bucketing"). |
timeout | number | 2 | Indicates the delay in seconds before it triggers a timeout when requesting campaigns via the Flagship decision api. |
When bucketing is running (
decisionMode="Bucketing"
), the polling will restart its interval period based on the moment when one of the following props changes after first rendering :
- envId
- visitorData
- initialModifications
- initialBucketing
- fetchNow
- activateNow
- enableConsoleLogs
- nodeEnv
- flagshipApi
- apiKey
- pollingInterval
visitorData
The visitorData
object takes the following arguments:
Argument | Type | Description |
---|---|---|
id | string | Required. Unique identifier for the current user. This can be an ID from your database or a session ID. If no value is passed, the SDK will automatically generate a unique ID. NOTE: The visitor id must be a string and can't be number |
context | object | Optional. JSON object of key-value pairs describing the user and device context |
onUpdate
The onUpdate
object has one argument with the following shape:
Key/Property | Description |
---|---|
fsModifications | Array. It contains the last modifications saved in cache. |
config | Object. The current configuration running on the SDK. |
onBucketingSuccess
The onBucketingSuccess
object has one argument with the following shape:
Key/Property | Description |
---|---|
status | String. Returns either 200 (fresh update) or 304 (no change). |
payload | Object. The latest bucketing data received. |
onBucketingFail
The onBucketingFail
object has one argument with the following shape:
Key/Property | Description |
---|---|
error | Object. Returns the error occurred and leads to bucketing polling failure. |
useFlagship
useFlagship
Demo:
This is the most used hook from the Flagship React Native SDK. It gives further functionalities such as getting current modifications of your actual visitor, send hit tracking, SDK status...
Returns an object.
useFlagship input
useFlagship input
Argument | Type | Description |
---|---|---|
options | object | See description |
useFlagship input options
useFlagship input options
Key/Property | Type | Description |
---|---|---|
modifications | object | Node param to specify Flagship modifications. See description |
useFlagship input options modifications
useFlagship input options modifications
Argument | Description |
---|---|
requested | Required. An array of objects for each modifications. See description |
activateAll | Optional. The value is false by default |
useFlagship input options modifications requested
useFlagship input options modifications requested
Argument | Description |
---|---|
key | Required. The name of the modification. |
defaultValue | Required. The default value if no value for this modification is found. |
activate | Optional. |
useFlagship output
useFlagship output
Key/Property | Type | Description |
---|---|---|
modifications | object | An object where each key is a modification with corresponding value |
getModificationInfo | function | Returns a promise with an object containing informations about modification matching the key specified in argument. See description |
synchronizeModifications | function | Updates campaigns targeting that match the current visitor context. See description |
hit | object | Gives you functions to send one or further hits. See description |
status | object | Gives you information about SDK current state. See description |
startBucketingPolling | function() | Call this function to start the bucketing manually. See description |
stopBucketingPolling | function() | Call this function to stop the bucketing manually. See description |
useFlagship output getModificationInfo
useFlagship output getModificationInfo
Returns Promise<object | null>
. (Typescript: GetModificationInfoOutput)
Argument | Type | Description |
---|---|---|
key | string | The modification key. |
useFlagship output synchronizeModifications
useFlagship output synchronizeModifications
Returns Promise<number>
.
Argument | Type | Default | Description |
---|---|---|---|
activateAllModifications | boolean | false | If set to true , all modifications will be activated. If set to false (default behavior), none will be activated. |
useFlagship output hits
useFlagship output hits
useFlagship output status
useFlagship output status
Key/Property | Description |
---|---|
isLoading | If true , the SDK isn't ready. |
lastRefresh | Date cast string with ISO format. This is the date corresponding to the most recent moment where modifications were saved in cache. |
useFlagship output startBucketingPolling
useFlagship output startBucketingPolling
Key/Property | Description |
---|---|
success | Boolean. If true means it succeed, false otherwise. |
reason | String. A message telling the reason in case of failure. |
useFlagship output stopBucketingPolling
useFlagship output stopBucketingPolling
Key/Property | Description |
---|---|
success | Boolean. If true means it succeed, false otherwise. |
reason | String. A message telling the reason in case of failure. |
useFsModifications
useFsModifications
Demo:
The useFsModifications
hook gives you the modifications saved in the SDK cache.
If the SDK cache is empty, it will always return modification's default values.
Returns Flagship modifications.
useFsModifications input
useFsModifications input
Argument | Type | Default | Description |
---|---|---|---|
modificationsRequested | Array(object) | Required | List of all modifications you're looking for. See description |
activateAllModifications | boolean | false | If set to true, all modifications will be activated. If set to false, none will be activated. NOTE: Setting this argument will override the activate attribute set in each element of the modificationsRequested array. |
useFsModifications input modificationsRequested
useFsModifications input modificationsRequested
Argument | Description |
---|---|
key | Required. The name of the modification. |
defaultValue | Required. The default value if no value for this modification is found. |
activate | Optional. Determines whether or not the modification is activated (if activateAllModifications is not set). |
useFsActivate
useFsActivate
Demo:
Returns void
.
useFsActivate input
useFsActivate input
Argument | Type | Default | Description |
---|---|---|---|
modificationKeys | Array(string) | Required | An array of modification keys. For each key, a HTTP request will be sent to activate the corresponding modification. |
applyEffectScope | Array(string) | [] | This argument behaves the same way as the second argument in the React.useEffect hook. It will listen for the array values and synchronize if it detects any changes. By default, it is triggered when the component where it's used is first rendered. |
Getting modifications
with useFlagship hook (1/3)
Demo:
import { useFlagship } from "@flagship.io/react-native-sdk";
const fsParams = {
modifications: {
requested: [
{
key: "btnColor",
defaultValue: "green",
activate: false,
},
],
},
};
const {
modifications: fsModifications,
status: fsStatus,
hit: fsHit,
} = useFlagship(fsParams);
with useFsModifications hook
Demo:
import { useFsModifications } from "@flagship.io/react-native-sdk";
const fsModifications = useFsModifications([
{
key: "btnColor",
defaultValue: "green",
activate: false,
},
]);
Campaign synchronization
with useFlagship hook (2/3)
Demo:
import { useFlagship } from "@flagship.io/react-sdk";
const { synchronizeModifications } = useFlagship();
return (
<>
<Button
onClick={() => {
synchronizeModifications(activateAllModifications)
.then((statusCode) => {
if (statusCode < 300) {
// Notify success...
} else {
// Notify failure...
}
})
.catch((error) => {
// Notify error...
});
}}
>
Trigger a synchronize
</Button>
</>
);
Campaign activation
with useFsActivate hook
Demo:
import { useFsActivate } from "@flagship.io/react-native-sdk";
const [toggle, setToggle] = React.useState(false);
useFsActivate(["btnColor", "otherKey1", "otherKey2"], [toggle]); // trigger an activate when "toggle" value change.
// insider render function:
<Button onClick={() => setToggle(!toggle)}>Trigger activate</Button>;
Hit Tracking
This section helps you track your users in your application and learn how to build hits in order to feed campaign goals. For more information about our measurement protocol, read our Universal Collect documentation.
There are four different types of hits available:
with useFlagship hook (3/3)
Demo:
import { useFlagship } from "@flagship.io/react-native-sdk";
const { hit: fsHit } = useFlagship();
// insider render function:
<Button
onClick={() => {
const mockHit = {
type: "Transaction",
data: {
transactionId: "12451342423",
affiliation: "myAffiliation",
totalRevenue: 999,
shippingCost: 888,
shippingMethod: "DHL",
currency: "USD",
taxes: 1234444,
paymentMethod: "creditCard",
itemCount: 2,
couponCode: "myCOUPON",
documentLocation:
"http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "myScreen",
},
};
fsHit.send(mockHit);
}}
>
Send a transaction hit
</Button>;
Hit types
Screen
import { useFlagship } from "@flagship.io/react-native-sdk";
const { hit: fsHit } = useFlagship();
<Button
onClick={() => {
const mockHit = {
type: "Screen",
data: {
documentLocation:
"http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testScreen",
},
};
fsHit.send(mockHit);
}}
>
Send a screen hit
</Button>;
Attribute | Type | Description |
---|---|---|
documentLocation | string | Required. Specifies the current URL of the page when the hit is sent. |
pageTitle | string | Required. Specifies the current name of the page when the hit is sent. |
The
Screen
hit isn't available yet in the Flagship reporting view.
Transaction
Attribute | Type | Description |
---|---|---|
transactionId | string | Required. The ID of your transaction. |
affiliation | string | Required. The name of the KPI that you will have inside your reporting. Learn more |
totalRevenue | number | Optional. Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts. |
shippingCost | number | Optional. The total shipping cost of your transaction. |
shippingMethod | string | Optional. The shipping method for your transaction. |
taxes | number | Optional. Specifies the total amount of taxes in your transaction. |
currency | string | Optional. Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code. |
paymentMethod | string | Optional. Specifies the payment method used for your transaction. |
itemCount | number | Optional. Specifies the number of items of your transaction. |
couponCode | string | Optional. The coupon code associated with the transaction. |
documentLocation | string | Optional. Specifies the current URL of the page when the hit is sent. |
pageTitle | string | Optional. Specifies the current name of the page when the hit is sent. |
import { useFlagship } from "@flagship.io/react-native-sdk";
const { hit: fsHit } = useFlagship();
<Button
onClick={() => {
const mockHit = {
type: "Transaction",
data: {
transactionId: "12451342423",
affiliation: "myAffiliation",
totalRevenue: 999,
shippingCost: 888,
shippingMethod: "DHL",
currency: "USD",
taxes: 1234444,
paymentMethod: "creditCard",
itemCount: 2,
couponCode: "myCOUPON",
documentLocation:
"http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "myScreen",
},
};
fsHit.send(mockHit);
}}
>
Send a transaction hit
</Button>;
Item
Attribute | Type | Description |
---|---|---|
transactionId | string | Required. The ID of your transaction. |
name | string | Required. The name of your item. |
price | number | Optional. Specifies the price for a single item/unit. |
code | string | Optional. Specifies the SKU or item code. |
category | string | Optional. Specifies the category that the item belongs to. |
quantity | number | Optional. Specifies the number of items purchased. |
documentLocation | string | Optional. Specifies the current URL of the page when the hit is sent. |
pageTitle | string | Optional. Specifies the current name of the page when the hit is sent. |
import { useFlagship } from "@flagship.io/react-native-sdk";
const { hit: fsHit } = useFlagship();
<Button
onClick={() => {
const mockHit = {
type: "Item",
data: {
transactionId: "0987654321",
name: "testItem",
price: 999,
code: "testCode",
category: "testCategory",
quantity: 123,
documentLocation:
"http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testItem",
},
};
fsHit.send(mockHit);
}}
>
Send a item hit
</Button>;
The
Item
hit isn't available yet in the Flagship reporting view
Event
Attribute | Type | Description |
---|---|---|
category | string | Required. Specifies the category of your event. NOTE: This value must be either 'Action Tracking' or 'User Engagement' . |
action | string | Required. The name of the KPI you will have inside the reporting. |
label | string | Optional. Specifies additional description of your event. |
value | number | Optional. Specifies the monetary value associated with an event (e.g. you earn 10 to 100 euros depending on the quality of lead generated). NOTE: this value must be non-negative. |
documentLocation | string | Optional. Specifies the current URL of the page when the hit is sent. |
pageTitle | string | Optional. Specifies the current name of the page when the hit is sent. |
import { useFlagship } from "@flagship.io/react-native-sdk";
const { hit: fsHit } = useFlagship();
<Button
onClick={() => {
const mockHit = {
type: "Event",
data: {
category: "User Engagement",
action: "signOff",
label: "Hello world",
value: 123,
documentLocation:
"http%3A%2F%2Fabtastylab.com%2F60511af14f5e48764b83d36ddb8ece5a%2F",
pageTitle: "testEvent",
},
};
fsHit.send(mockHit);
}}
>
Send a event hit
</Button>;
Release note
Take a look to the Release note.
Updated 3 months ago