React Native SDK
Getting Started
Visit the React Native docs to get started with a React Native project.
Visual Editor
Please note that the React Native SDK does not support visual editing. The visual editor is only supported on the iOS and Android SDKs.
Install the taplytics-react-native
package:
As of 2.1.0, Taplytics now supports 0.60.0 React Native projects and above! To get started, just run:
yarn add taplytics-react-native --save
If you previously have installed Taplytics, you may be shown a warning if you haven't unlinked your previously linked projects. To fix this, simply run the command:
yarn unlink taplytics-react-native
For react native versions <0.60, automatic linking is not supported and you will need to run the manual linking command which should link the package on both iOS and android.
react-native link taplytics-react-native
iOS Setup
-
Navigate to your
/ios
folder and execute the commandpod install
. Taplytics will install along with the React dependencies. -
Initialize Taplytics through the iOS app.
-
(Optional) Add any additional start options needed on initialization.
Note: For react native version <0.60 or if your project is not utilizing CocoaPods a manual installation of the Taplytics iOS SDK will be required.
Android Setup
- Navigate to your Project's build.gradle file and add the following url to the SDK.
repositories {
maven { url "https://github.com/taplytics/Taplytics-Android-SDK/raw/master/AndroidStudio/" }
}
-
Follow the steps in the Android docs to Initialize Taplytics in the App.
-
(Optional) Add any additional start options needed on initalization.
Start making Experiments and sending Push Notifications to your users.
This module wraps most native SDK methods in Javascript, allowing you to access features such as dynamic variables, code blocks and event logging in the React Native environment.
Be sure to import Taplytics into your react application according to the version of the React Native SDK installed.
Version 2.x
import Taplytics from 'taplytics-react-native';
Version 3.x
import * as Taplytics from 'taplytics-react-native'
// OR
import { useFeatureFlag, logEvent } from 'taplytics-react-native'
Follow the rest of the guide or jump to the following quick links:
User Attributes
Set User Attributes
Taplytics.setUserAttributes(customUserAttributes);
Use the setUserAttributes
method to send Taplytics a JSON Object of user info. The possible fields for User Attributes are listed below. You can add any other custom attributes to the customData
object and it will also be passed to Taplytics.
customAttributes
Type
customAttributes
TypePARAMETER | TYPE |
---|---|
email | string |
user_id | string |
firstname | string |
lastname | string |
name | string |
age | number |
gender | string |
customData | object |
Example
await Taplytics.setUserAttributes({
email: '[email protected]',
name: 'John Doe',
age: 25,
gender: 'male',
avatarurl: 'https://someurl.com/someavatar.png',
customData: {
someCustomAttribute: 50,
paidSubscriber: true,
subscriptionPlan: 'yearly',
},
});
Resetting user attributes or Logging out a user
Taplytics.resetAppUser()
Once a user logs out of your app, their user attributes are no longer valid. Use the resetAppUser
method to reset their attributes.
Track Events
Automatic Events
Some events are automatically tracked by Taplytics and will appear on your dashboard. These events are:
- App Start
- App background
No changes are needed in your code for this event tracking to occur.
Custom Events
Taplytics.logEvent(eventName, value, customAttributes)
Log custom event's using the logEvent
method.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
eventName | string | v2.x : Yesv3.x : Yes | The name of the event. |
value | number | v2.x : Yesv3.x : No | A numerical value associated with the event.v3.x : This is an optional parameter, if no value is passed it is initialized to 0. |
customAttributes | object | v2.x : Yesv3.x : No | A custom object that gets associated with the event.v3.x : This is an optional parameter, if no value is passed it is initialized with an empty object. |
Examples
// For v2.x and v3.x with value and customAttributes params
Taplytics.logEvent('eventName', 5, {
'custom attribute': 'custom attribute value',
});
Taplytics.logEvent('eventName', 0, {});
Taplytics.logEvent('eventName');
Revenue Logging
Taplytics.logRevenue(eventName, value, customAttributes)
It's also possible to log revenue. Revenue logging works the same way as event logging, except you will need to utilize the logRevenue
method.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTIONS |
---|---|---|---|
eventName | string | v2.x : Yesv3.x : Yes | The name of the revenue event. |
value | number | v2.x : Yesv3.x : No | A numerical value associated with the revenue event.v3.x : This is an optional parameter, if no value is passed it is initialized to 0. |
customAttributes | object | v2.x : Yesv3.x : No | A custom object that gets associated with the revenue event.v3.x : This is an optional parameter, if no value is passed it is initialized with an empty object. |
Examples
// For v2.x and v3.x with value and customAttributes params
Taplytics.logRevenue('Revenue Name', 100, {
'custom attribute': 'custom attribute value',
});
Taplytics.logRevenue('Revenue Name', 0, {});
Taplytics.logRevenue('Revenue Name');
Dynamic Variables & Code Blocks
Taplytics variables are values in your app that are controlled by experiments. Changing the values can update the content or functionality of your app. Variables are reusable between experiments and operate in one of two modes: synchronous or asynchronous. You can use both sync and async variables from within your app.
Synchronous Dynamic Variables
Taplytics.newSyncVariable(name, defaultValue);
Loading properties prior to retrieving variable value
The value of these variables will be determined immediately, ie. the SDK will not wait for properties to be loaded from the server. Thus, if you want to ensure that the variables have their correct variables based on your experiment segmentation, you must initialize them after the properties have been loaded from the server. This module provides a callback to achieve this. The callback returns back an event subscriber that can be used to cleanup the event listener using the
remove
function.
Synchronous variables are guaranteed to have the same value for the entire session and will have that value immediately after construction. The type of the variable will be inferred from the type of value passed in as the default. This method returns a promise which resolves with the value of the synchronous variable.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
name | string | Yes | The name of the dynamic variable. |
defaultValue | string | boolean | number | object | Yes | Default value to be utilized for the dynamic variable. |
Example
const subscriber = Taplytics.propertiesLoadedCallback(async (loaded) => {
const variableValue = await Taplytics.newSyncVariable('My Variable', 'default')
});
// Clean up subscriber
subscriber.remove();
Asynchronous Dynamic Variables
Taplytics.newAsyncVariable(name, defaultValue, callback);
newAsyncVariable Usage
v3.x: The
newAsyncVariable
method returns an event subscriber that can be used to cleanup the event listener using theremove
function. This should be done to ensure that there is no memory leaks within your app.
Asynchronous variables take care of insuring that the experiments have been loaded before returning a value. This removes any danger of tainting the results of your experiment with bad data. What comes with the insurance of using the correct value is the possibility that the value will not be set immediately. If the variable is used before the experiments are loaded, you won't have the correct value until the experiments have finished loading. If the experiments fail to load, then you will be given the default value, as specified in the methods constructor.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
name | string | Yes | The name of the dynamic variable. |
defaultValue | string | boolean | number | object | Yes | Default value to be utilized for the dynamic variable. |
callback | (variableValue) => void | Yes | A function that runs when the dynamic variable has been evaluated or updated, it receives the dynamic variable value as the argument. |
Examples
Taplytics.newAsyncVariable('My Variable', 'default value', (variableValue) => {
// Use variableValue
});
const subscriber = Taplytics.newAsyncVariable('My Variable', 'default value', (variableValue) => {
// Use variableValue
});
subscriber.remove();
Code Blocks
Taplytics.runCodeBlock(name, codeBlock);
Similar to Dynamic Variables, Taplytics has an option for 'Code Blocks'. Code blocks are linked to Experiments through the Taplytics website very much the same way that Dynamic Variables are, and will be executed based on the configuration of the experiment through the Taplytics website. A Code Block is a callback that can be enabled or disabled depending on the variation. If enabled, the code within the callback will be executed. If disabled, the variation will not get the callback.
A Code Block can be used alongside as many other Code Blocks as you would like to determine a combination that yields the best results. You can register functions as code blocks to be run or not depending on your experiment variation. By default, a code block will not run unless enabled on the Taplytics Dashboard. It must be enabled for a Variation before it will run.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
name | string | Yes | The name of the code block variable. |
codeBlock | () => void | Yes | A function that will run if the code block variable is activated. |
Example
Taplytics.runCodeBlock('Code Block Variable name', () => {
// Code block function
});
Currently Running Experiments and Variables
Get Variables
Taplytics.getVariables();
This method returns an object with experiment variables' keys and values. It only keeps track of variables that have been fetched by either newAsyncVariable
or newSyncVariable
.
Variables Changed Listener
Taplytics.registerVariablesChangedListener(callback);
You can also register a function to be called whenever the variables from getVariables
changes. Only one callback function can be registered at a time. Calling this method again will overwrite the previous callback.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
callback | (variables) => void | Yes | A function that is invoked whenever an experiments' variable is updated. |
Running Experiments and Variations
Taplytics.getRunningExperimentsAndVariations();
Loading properties prior to retrieving experiments
This function runs asynchronously, as it waits for the updated properties to load from Taplytics' servers before returning the running experiments.
If you want to see when the experiments have been loaded by Taplytics, you can wrap this in the
propertiesLoadedCallback
method.
Use the getRunningExperimentsAndVariations
method to determine which variations and experiments are running on a given device.
Example
const subscriber = Taplytics.propertiesLoadedCallback(async () => {
const runningExperiments = await Taplytics.getRunningExperimentsAndVariations()
})
// Clean up subscriber
subscriber.remove()
Feature Flags
Feature Flag Enabled
Taplytics.featureFlagEnabled(key);
Loading properties prior to determining feature flag value
The value of
featureFlagEnabled
will be determined immediately, ie. the SDK will not wait for properties to be loaded from the server. Thus, if you want to ensure that the feature flags have their correct values based on your experiment segmentation, you must initialize them after the properties have been loaded from the server.This module provides the
propertiesLoadedCallback
method to achieve this. The method returns back an event subscriber that can be used to cleanup the event listener using theremove
function.
Use this method to determine if a particular feature flag is enabled.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
key | string | Yes | The key of the feature flag. |
Example
const subscriber = Taplytics.propertiesLoadedCallback(async () => {
const isEnabled = await Taplytics.featureFlagEnabled('featureFlagKey')
if (isEnabled) {
// Put feature code here, or launch feature from here
}
})
// Clean up subscriber
subscriber.remove()
Running Feature Flags
Taplytics.getRunningFeatureFlags()
This method is used to determine which feature flags that are running on a given device. The method returns a promise that resolves to an object with running feature flags' names and their associated key.
Example
const runningFeatureFlags = await Taplytics.getRunningFeatureFlags();
Sessions
Start New Session
Taplytics.startNewSession();
startNewSession
can be used to manually force a new user session (ex: A user has logged in / out). This method returns a promise that resolves when the session has been created.
New Session Listener
Taplytics.setTaplyticsNewSessionListener(callback);
This listener can be used to register a callback for when a new session is created.
Parameters
NAME | TYPE | REQUIRED | DESCRIPTION |
---|---|---|---|
callback | () => void | Yes | A function that gets executed when a new session is created. |
Retrieving Session Info
import { getSessionInfo } from 'taplytics-react-native/lib/user'
getSessionInfo();
This method can be used to retrieve select information about a session at a given time. This method returns the user's Taplytics identifier; appUser_id
, and current session ID; session_id
.
Example
const { appUser_id, session_id } = await Taplytics.getSessionInfo()
Push Notifications
Setting up Push Notifications
Due to the nature of push notifications and their dependencies on the specific platforms, setup for each individual platform must be performed natively.
Push Event Listeners
It's possible to attach listeners to the three push notification events handled by the Taplytics SDK. These are push received, push dismissed and push opened. Use the following three methods:
Taplytics.registerPushOpenedListener((value) => {
// Do something
})
Taplytics.registerPushReceivedListener((value) => {
// Do something
})
//Only available on android
Taplytics.registerPushDismissedListener((value) => {
// Do something
})
You can register multiple callbacks for the same event, and all will be executed.
Before these event listeners trigger, push notifications must be set up fully on each respective platform.
iOS
To register for push notifications, it is possible to do so by calling:
// iOS available only
Taplytics.registerPushNotifications()
To set up push notifications on iOS natively, please follow the documentation here:
iOS SDK - Push Notifications
Other Push Event Listeners
On iOS, its also possible to use the built-in React Native push notification module, which can be found here
Android
If you wish to use Push Notifications on Taplytics, you must add the following permissions (replace com.yourpackagename
with your app's package name) to your Android Manifest:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.yourpackagename.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.yourpackagename.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
And you must add the following receiver and service under your application tag:
<receiver
android:name="com.taplytics.react.TRNBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
<intent-filter>
<action android:name="taplytics.push.OPEN" />
<action android:name="taplytics.push.DISMISS" />
</intent-filter>
</receiver>
<service android:name="com.taplytics.sdk.TLGcmIntentService" />
Then add the following to your build.gradle:
compile("com.google.android.gms:play-services-gcm:9.+")
Rich Push, Advanced Usage, and more Android Push Features
To see more push features available to android, please view the Android push documentation.
Android SDK - Push Notifications
Hooks
Introducing Hooks
The Taplytics React Native Hooks are functions that allow you to hook into the Taplytics React Native SDK. The hooks manage the state and lifecycle updates so that you can focus on building your app rather than instrumenting the SDK.
Installation
Hooks are only available on v3 Release Candidate
At the moment hooks are only available within version
3.0.0-rc.x
of thetaplytics-react-native
package. To install the release candidate version follow the command below.
yarn add taplytics-react-native@next
Migrating from v2.x to v3.x
The package has switched away from default exports and now exports each of it's methods individually for improved discoverability and autocompletion.
If you're migrating over from version 2.x
of the package and want to make the transition as easy as possible, you will need to make sure that the import statements have been changed as shown below.
import * as Taplytics from 'taplytics-react-native'
// OR
import { useFeatureFlag, logEvent } from 'taplytics-react-native'
Using Hooks
Taplytics provides 4 hooks that can be used within React's functional components for easier usage of the core Taplytics React Native SDK.
TaplyticsProvider
(Required)
TaplyticsProvider
(Required)A <TaplyticsProvider />
component is included which needs to be wrapped around the whole app.
import 'react-native-gesture-handler'
import * as React from 'react'
import { TaplyticsProvider } from 'taplytics-react-native'
export default function App() {
return <TaplyticsProvider>{/* Rest of your app code */}</TaplyticsProvider>
}
useFeatureFlag
useFeatureFlag
useFeatureFlag
is a hook which can be used to determine whether a certain feature flag is enabled. If a parameter is not provided to the useFeatureFlag
hook, it will return an object with all running feature flag's names and their associated keys.
The useFeatureFlag
returns an array which can be destructed as shown in the example below. The first property in the array is the value of a feature flag or an object of all running feature flags, the second property is a meta data object which contains an error
and loading
property.
const SomeComponent = () => {
// Returns a boolean dependent if exampleFeatureFlag is enabled.
// Also returns the loading and error context values.
const [flagValue, { loading, error }] = useFeatureFlag('exampleFeatureFlag')
// Returns an object of all running feature flags.
// The object key is the name and the value is the key of the feature flag
// Example: { "Example Feature Flag" : "exampleFeatureFlag" }
const [allFeatures] = useFeatureFlag()
return (
<View>
<Text>Feature flag is {flagValue ? `active` : `inactive`} </Text>
<Text>{JSON.stringify(allFeatures)} </Text>
</View>
)
}
useVariable
useVariable
useVariable
is a hook that can be utilized to fetch the value of a dynamic variable. The hook will also run whenever the value of the variable is updated. The hook takes in a name parameter as well as a default value. This default value is returned in a situation where there is an error loading the variable.
The hook also returns an array that can be destructed to retrieve the value of the dynamic variable and a meta data object. The meta data object has an error
and loading
property, which are completely independent to each useVariable
hook.
const SomeComponent = () => {
// Returns the value of the 'workHours' dynamic variable.
// It also returns a loading and error property.
const [workHoursValue, { loading, error }] = useVariable('workHours', 8)
return (
<View>
<Text>{`The standard work hours are ${workHoursValue}`} </Text>
</View>
)
}
useCodeBlock
useCodeBlock
The useCodeBlock
hook can be used to run a code block function if the code block variable is activated. The hook takes in a name, callback parameter and a dependency array parameter (similar to the useEffect
second parameter). The callback is only triggered if the code block variable's value is true. It will also be triggered any time that a dependency updates, if client requires that the hook only be run once, an empty array can be passed through to the final parameter.
This example shows the useCodeBlock
hook only being triggered once.
const HomeScreen = ({ showModal }) => {
// The callback will only run once due to the empty array []
useCodeBlock(
'showQuestionnaire',
() => {
showModal(<Questionnaire />)
},
[],
)
return <Home />
}
This is an example of the useCodeBlock
hook being utilized to trigger the callback whenever the orderCount variable updates.
const OrderScreen = ({ triggerConfetti }) => {
const [orderCount, setOrderCount] = useState(0)
// This codeblock will be triggered whenever the `orderCount`
// state variable updates
useCodeBlock('showConfetti', triggerConfetti, [orderCount])
return <Order />
}
useRunningExperiments
useRunningExperiments
This hook can be utilized to get the names of the running experiments and which variation they are running at. The hook can act as a replacement for the getRunningExperimentsAndVariations
core SDK method.
The useRunningExperiments
hook returns an array that can be destructed to retrieve the running experiments as well as a meta data object. The meta data object contains an error
and loading
property.
const DebugScreen = ({ showModal }) => {
// Returns an object that contains the experiments running as well as which
// variation they are running on.
// Example: { "Example Experiment" : "baseline" }
const [runningExperiments, { loading, error }] = useRunningExperiments()
return <DebugList experiments={runningExperiments} />
}
Updated over 1 year ago