React-native v3.3.X
Introduction
SDK overview
🚧 Flagship React SDK only works with React hooks
Our React SDK only works with react hooks, if you want to use without it, you should use our Javascript SDK
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 Flags
Manage visitor consent
Activate campaigns
Send hits to our Universal Collect
Manage visitor cache
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
Typescript code supported
Getting started
Initialization
There are four steps to follow to get started with the React Flagship SDK.
Install the node module
📘 Information
Please ensure that you have also installed the @react-native-async-storage/async-storage package. If it's not already in your project, you'll need to add it separately.
Import the Flagship React provider
In most cases, do this in yourApp.js file to wrap your entire app with the provider.
Initialize the provider
You must at least include the required props likeenvId, apiKey, visitorData.
Use a Flagship hook in a component
In most case, you will get the desired flags.
API Reference
FlagshipProvider
Here is the full list of props available to use inside the FlagshipProvider React component:
envId
\
📘
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
apiKey
decisionMode
📘
Any change of props
visitorDatawill fetch flags automatically.On SDK initialization, if the props
visitorDatais null, no visitor will be initialized until set
\
visitorData
The visitorData object takes the following arguments:
id
\
Decision Mode
DECISION-APIMode (by default)
When the SDK is running in API mode, the campaign assignments and targeting validation will be run through our Decision API. In this mode, each time a new Decision is required, it will create an HTTPS request to the API.
This mode is used by default for all our SDK.
BucketingMode
When the SDK is running in Bucketing mode, the SDK downloads all the campaigns configurations at once in a single bucketing file so that variation assignment can be computed client-side by the SDK. This bucketing file is stored in cache and will only be downloaded again when campaign configurations are modified in the Flagship interface. Learn more
DecisionMode is an enum defined decision type
DECISION_API
API
string
Flagship SDK mode Decision API
BUCKETING
BUCKETING
string
Flagship SDK mode bucketing
\
onUpdate
The onUpdate object has one argument with the following shape:
fsModifications
Array or null. It contains the last modifications saved in cache. When null, it means the SDK still not ready. You can check the SDK status with other attributes.
config
Object. The current configuration running on the SDK.
status
Object. Contains informations about the actual SDK status. (Details below 👇)
status object shape:
isLoading
Boolean. When true, the SDK is still not ready to render your App otherwise it'll use default modifications.
isSdkReady
Boolean. true after it has fully finished initialization tasks, false otherwise.
isVisitorDefined
Boolean. When true the flagship visitor instance is truthy, false otherwise.
hasError
Boolean. true when an error occured inside the SDK, false otherwise.
lastRefresh
String or null. The last update date occured on the flagship visitor instance.
firstInitSuccess
String or null. When null no initialization succeed yet. When string contains stringified date of last successful initialization.
\
onBucketingSuccess
The onBucketingSuccess function has one argument with the following shape:
status
String. Returns either 200 (fresh update) or 304 (no change).
payload
Object. The latest bucketing data received.
\
onBucketingFail
The onBucketingFail function has one argument
error
object
Returns the error occurred
\
onBucketingUpdated
The onBucketingUpdated function has one argument
lastUpdate
Date
Get the date of the latest update
\
statusChangedCallback
The statusChangedCallback function has one argument
\
onUserExposure
The onUserExposure function has one argument with the following shape:
param
UserExposureInfo
Get data from exposed flag
UserExposureType shape
flagData
\
OnVisitorExposed
In some cases, you'll need to send information about the exposure (When a flag has been seen by your visitor), like sending visitor and flag data to third parties.
To centralize it, we provide a callback in the configuration option of the SDK.
The OnVisitorExposed function has one argument with the following shape:
param
OnVisitorExposed
Get data from exposed flag
OnVisitorExposed shape
exposedVisitor
exposedVisitor object shape
id
string
visitor id
anonomousId
string
anonymous id
context
Record<string, string|number|boolean>
visitor context
fromFlag object shape
key
string
flag key
value
unknown
flag value
defaultValue
unknown
flag default value
\
Here is an example on how to use this callback:
Learn more about getting flags
\
onLog
The onLog function has 3 arguments
tag
string
Get the function that triggered the log
message
string
Get a description of the log
Usage :
\
FlagshipStatus
FlagshipStatus is an enum defining the different status of Flagship SDK
NOT_INITIALIZED
0
int
It is the default initial status. This status remains until the sdk has been initialized successfully.
STARTING
1
int
Flagship SDK is starting.
POLLING
2
int
Flagship SDK has been started successfully but is still polling campaigns.
READY_PANIC_ON
3
int
Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refresh this status.
READY
4
int
Flagship SDK is ready to use.
\
Flag data shape:
key
string
Flag name
campaignId
string
Campaign ID
campaignName
string
Campaign name
variationGroupId
string
Variation group ID
variationGroupName
string
Variation group name
variationId
string
The variation ID assigned to the visitor
variationName
string
Variation name
isReference
boolean
Specify if its the reference variation
slug
string
campaign slug
value
any
Value of flag
\
LogLevel
LogLevel is an enum defined the level of log to receive
NONE
0
int
Logging will be disabled.
EMERGENCY
1
int
Only emergencies will be logged
ALERT
2
int
Only alerts and above will be logged.
CRITICAL
3
int
Only critical and above will be logged.
ERROR
4
int
Only errors and above will be logged.
WARNING
5
int
Only warnings and above will be logged.
NOTICE
6
int
Only notices and above will be logged.
INFO
7
int
Only info logs and above will be logged.
DEBUG
8
int
Only debug logs and above will be logged.
ALL
9
int
Everything will be logged.
\
IFlagshipLogManager
The aims of this Interface is to define methods that an object must have in order to receive Flagship SDK logs
message
Usage :
\
trackingManagerConfig
The SDK allows you to send hits with a batching system, there is 3 options to configure it : cacheStrategy, poolMaxSize and batchIntervals.
The advantage of batch processing with the TrackingManager is to use less network traffic, avoid loss of hits with cache, and catch all hits that would failed and resend them.
All hits will first be added into an internal pool as they are emitted by visitors. And This pool is going to be emptied by batching all hits from the pool and then sending the batch when the poolMaxSize is reached or when the batchIntervals timer is triggered.
If a batch fails, all of the hits inside the failed batch will be added back into the pool for future iteration, the cache will be updated depending on the cache strategy used.
At any time, when your app is about to close or crash, you should call useFlagship().close() or Flagship.close() to batch and send all hits that are in the pool.
options:
cacheStrategy
\
CacheStrategy
cacheStrategy is an enum defining the different caching strategies
CONTINUOUS\_CACHING
📘
The
CONTINUOUS_CACHING strategy(recommended) should be used when your application is running in an environment where the probability of data loss is high.Keep in mind that this strategy can do a lot of database I/O depending on how many hits your visitor can send.
The
PERIODIC_CACHING strategyshould be used when your application sends a lot of hits and the probability of data loss is low.In this strategy, the number of I/Os in the database is low.
\
useFlagship
Demo:
This is the most used hook from the Flagship React Native SDK. It gives further functionalities such as getting current flags of your actual visitor, sending hit tracking, checking SDK status...
Returns an object. (Typescript: UseFlagshipOutput)
useFlagship output
visitorId
useFlagship output setConsent
Set if visitor has consented for protected data usage.
setConsent(hasConsented: boolean): void;
It has one argument :
hasConsented
boolean
True if the visitor has consented false otherwise.
\
useFlagship output updateContext
Update the visitor context values, matching the given keys, used for targeting. A new context value associated with this key will be created if there is no previous matching value.
updateContext(context: Record<string, string | number | boolean>): void
It has one argument :
context
object
A Set of keys, values.
\
useFlagship output clearContext
Clear the actual visitor context
clearContext(): void
\
useFlagship output fetchFlags
In DecisionApi Mode this function calls the Flagship Decision API to run campaign assignments according to the current visitor context and retrieve applicable flags.
In bucketing Mode, it checks bucketing file, validates campaigns targeting the visitor, assigns a variation and retrieve applicable flags
fetchFlags(): Promise<void>
\
useFlagship output getFlag
Return a Flag object by its key. If no flag match the given key an empty flag will be returned. Call exists() to check if the flag has been found.
getFlag<T>(key:string, defaultValue: T) : IFlag<T>
\
key
String
key associated to the flag.
defaultValue
T
flag default value.
🚧
Default value must be one of the following type :
string,number,boolean,object,array.
\
useFlagship output authenticate
Authenticate anonymous visitor
authenticate(visitorId: string): void
visitorId
string
required
id of the new authenticated visitor.
\
useFlagship output unauthenticate
This function change authenticated Visitor to anonymous visitor
unauthenticate(): void
\
useFlagship output hit
useFlagship output status
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.
🚧
All useFlagship hook methods will be deactivated when visitor is not initialized except getFlag
\
useFsFlag
This hook returns a Flag object by its key. If no flag match the given key an empty flag will be returned.
useFsFlag<T>(key: string, defaultValue: T) : IFlag<T>
\
key
String
key associated to the flag.
defaultValue
T
flag default value.
\
Flag class api
getValue function
To retrieve flag current value, simply call value() method of the Flag object.
getValue(visitorExposed:boolean):Tfunction
Returns the value from the assigned campaign variation or the Flag default value if the Flag does not exist, or if types are different.
visitorExposed
🚧
Will return default value when visitor is not yet initialized
\
metadata property
You may need to send campaign IDs or variation IDs to a third party for reporting and/or analytics purposes. It is possible to retrieve campaigns metadata for a specific Flag.
\
metadata:IFlagMetadata
Return the campaign information metadata or an empty object if the Flag doesn't exist or if the default value type does not correspond to the Flag type in Flagship.
campaignId
string
Campaign name
campaignName
string
Campaign name
variationGroupId
string
Variation group ID
variationGroupName
string
Variation group name
variationId
string
The variation ID assigned to the visitor
variationName
string
Variation name
isReference
boolean
Specify if its the reference variation
\
visitorExposed function
By default when the method getValue() is called, The SDK considers that the visitor have seen the effets of your Flag, unless you pass false to getValue(). In this case you will have to call visitorExposed().
There are two ways for exposing a visitor to a flag:
Pass an
visitorExposed=trueparameter to the getValue() method.Use the following visitorExposed() method from the Flag instance.
visitorExposed(): Promise<void>
Tells Flagship the visitor have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. No visitor exposure will be sent if the Flag doesn't exist or if the default value type do not correspond to the Flag type in Flagship.
userExposed(): Promise<void>deprecated
Tells Flagship the visitor have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. No visitor exposure will be sent if the Flag doesn't exist or if the default value type do not correspond to the Flag type in Flagship.
🚧
userExposedis deprecated, usevisitorExposedinstead
\
exists function
This method will return true if a Flag exists in Flagship
exists(): boolean
\
Getting flags
with useFsFlag hook
Demo:
with useFlagship hook
Demo:
\
Report a Flag exposure
\
Fetching Flags
with useFlagship hook
Demo:
\
Managing visitor consent
With Flagship React Native SDK, you can manage visitor consent for data privacy usage. When False, campaign activation and hits will be disabled.
There are 2 ways to set visitor consent :
Set
hasConsentedkey to true or false in props VisitordData of FlagshipProviderUse
setConsentmethod ofuseFlagshiphook
\
Demo:
📘
When a visitor sets consent to false, the data collection features (visitorExposed and sendHit) will be deactivated for them and all hits related to the visitor will be flushed from the pool and the cache.
\
Update context with predefined keys of context
Demo:
Learn more about predefined keys of context
\
Experience continuity
🚧
Make sure that the experience continuity option is enabled on the flagship platform before using those methods.
It might happen that a visitor from your app is not yet recognized and is being authenticated (and recognized) later on...
From there, we provide the ability to ensure that during such transition, your visitor will keep same experience (meaning targetting still the same campaign's variations and thus same modifications).
In order to do a successful experience continuity, we will have to distinguish when the visitor is anonymous or authenticated.
Let's assume basic scenario to understand how things work:
1. Your visitor arrives on your app for the first time
We need to initialize the visitor but as we don't know anything about this visitor, we'll create a random visitor id or let the SDK do it for us. You can also specify some visitor context if necessary.
Whatever how it has been set, the actual visitor id will be what we call its anonymous id.
📘
Be aware that when you do not specify a visitor id, as
enableClientCacheis enable by default, the SDK will try to find a previous visitor experience. If so, the new visitor will have the same visitor id as it was during the previous visitor session. From there, no id will be automatically generated.
Your visitor is signing in.
We need to set the value of visitorData.isAuthenticated to true or call the method authenticate of useFlagship hook.
Moreover, the visitor id set should be an existing visitor id (that has previously seen specific campaign's flags) in order to make the experience continuity effective.
This new visitor id is what we call its authenticated id.
The visitor is updated as authenticated, keeping the previous variations from campaigns that are still matched and thus gives you same modifications as before being logged in.
📘
Keep in mind that if the visitor also has its context changed, you might still have changes on flags as your visitor might target new campaigns.
Your visitor decide to sign out.
We need to set the value of visitorData.isAuthenticated back to false.
If you want to keep the same visitor (anonymous) experience as before, depending on the value of prop enableClientCache, you'll have to:
enableClientCache=true: the sdk will put back the previous anonymous id automatically based on data from cache.
enableClientCache=false: you should specify invisitorData.id\prop, the same value as you set in step 1.
If you need a completly brand new visitor experience, you should put a new visitor id in visitorData.id prop instead:
Hit Tracking
\
This section helps you track your visitors in your application and learn how to build hits in order to feed your reports. For more information about our measurement protocol, read our Universal Collect documentation.
There are five different types of Hits available:
Page
Screen
Transaction
Item
Event
HitType
PAGE
string
PAGEVIEW
Visitor has seen a URL.
SCREEN
string
SCREENVIEW
Visitor has seen a screen.
TRANSACTION
string
TRANSACTION
Visitor has made a transaction.
ITEM
string
ITEM
Item bought in a transaction.
EVENT
string
EVENT
Visitor has made a specific action.
\
They must all be built and sent with the following functions from the`useFlagship hook
\
\
useFlagship output hit.send function
Send Hit to Flagship servers for reporting.
send (hit: IHit): Promise<void>
\
useFlagship output hit.sendMultiple function
Send Hits to Flagship servers for reporting.
sendMultiple(hits: IHit[]): Promise<void>
\
Hit common optional parameters
\
\
userIp
String
(Optional) Visitor IP
screenResolution
string
(Optional) Screen resolution.
locale
String
(Optional) Visitor language
sessionNumber
string
(Optional) Session number
\
Page
\
This hit should be sent each time a visitor arrives on a new page.
\
A hit of type
Pagehas the following structure:
documentLocation
String
required
Valid url.
\
Screen
\
This hit should be sent each time a visitor arrives on an interface on client side.
\
A hit of type
Screenhas the following structure:
documentLocation
String
required
Name of screen.
\
Transaction
\
This hit should be sent when a visitor completes a Transaction.
\
A hit of type TRANSACTION has the following structure:
transactionId
String
required
Unique identifier for your transaction.
totalRevenue
float
optional
Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts.
shippingCosts
float
optional
The total shipping cost of your transaction.
shippingMethod
String
optional
The shipping method for your transaction.
taxes
float
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
int
optional
Specifies the number of items in your transaction.
couponCode
String
optional
Specifies the coupon code used by the customer in your transaction.
\
Item
\
This hit is used to link an item with a transaction. It must be sent after the corresponding transaction hit.
\
A hit of type ITEM has the following structure:
transactionId
String
required
Unique identifier for your transaction.
productName
String
required
Name of your item.
productSku
String
required
Specifies the SKU or item code.
itemCategory
String
optional
Specifies the category that the item belongs to.
itemPrice
float
optional
Specifies the price for a single item/unit.
itemQuantity
int
optional
Specifies the number of items purchased.
Event
This hit can be used for any event (e.g. Add To Cart click, newsletter subscription).

