• HOME
  • INTEGRATIONS
  • SDKS
  • GUIDES
  • API DOCS
No results for ""
EXPAND ALL
launchdarkly.com

EDIT ON GITHUB

React Native SDK reference

Read time: 5 minutes
Last edited: Dec 01, 2020
SDK Version Compatibility

The latest version of the SDK is compatible with Xcode 11.4 and React Native 0.63. For compatibility with earlier React Native versions, please refer to older SDK versions.

This reference guide documents all of the methods available in our React Native SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read React Native SDK GitHub repository. The online API docs contain the programmatic definitions of every type and method. Additionally you can clone and run a sample application using this SDK.

To learn more about the specific configuration options that are available in this SDK, read the SDK's API docs.

Getting Started

Expo Usage

The LaunchDarkly React Native Client SDK does not work with Expo because the SDK uses native modules. Please consider using ExpoKit.

Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your React Native code.

The first step is to install the LaunchDarkly SDK as a dependency. Add the LaunchDarkly npm dependency to your project and link it to your React Native project.

1npm install --save launchdarkly-react-native-client-sdk
2cd ios/
3pod install

You will need a Podfile in your ios/ directory. Once you've written your Podfile, run pod install in the ios/ directory. This SDK currently requires Xcode 10.2.1 (it is compatible with Xcode 10.3) and is compiled against Swift 5.

use_frameworks! and undefined symbols errors
As of v2.1.0 use_frameworks! is not necessary in the Podfile. If you encounter an undefined symbols error when building without use_frameworks! in your Podfile you will need to create a new empty Swift file and accept the prompt to create a matching Objective-C bridging header. If you are building for multiple platforms, add those as targets for the bridging header. If you're still having trouble resolving the undefined symbols error, clean and rebuild and try again.
1platform :ios, '10.0'
2require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
3
4target 'YOUR_MODULE_NAME' do
5 # Pods for ReactNativeRestwrapper
6 pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
7 pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
8 pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
9 pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
10 pod 'React', :path => '../node_modules/react-native'
11 pod 'React-Core', :path => '../node_modules/react-native'
12 pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
13 pod 'React-Core/DevSupport', :path => '../node_modules/react-native'
14 pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
15 pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
16 pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
17 pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
18 pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
19 pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
20 pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
21 pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
22 pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
23 pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native'
24
25 pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
26 pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
27 pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
28 pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
29 pod 'React-callinvoker', :path => "../node_modules/react-native/ReactCommon/callinvoker"
30 pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
31 pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
32
33 pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
34 pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
35 pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
36
37 #launchdarkly-react-native-client-sdk dependencies
38 pod 'LaunchDarkly', '4.5.0'
39
40 use_native_modules!
41end

Once the SDK is downloaded and saved in package.json and the other install steps are complete, you'll need to import it into your project:

1import LDClient from 'launchdarkly-react-native-client-sdk';

Once the SDK is installed and imported, you'll want to create a single, shared instance of LDClient, passing in the client and user configuration objects. To create a client instance, you need your environment's mobile key (available on your account settings page). Mobile keys are not secret. You can expose them in your client-side code with no risk.

1let client = new LDClient();
2
3let clientConfig =
4 { "mobileKey": "YOUR_MOBILE_KEY",
5 "stream": true,
6 "offline": false
7 };
8
9let userConfig = { "key": "user_key" };
10
11await client.configure(clientConfig, userConfig);

Lastly, when your application is about to terminate, shut down LDClient. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.

1client.close();
Mobile Keys

Be sure to use a mobile key from your Environments page.

Never embed a server-side SDK key into a mobile application.

Client Configuration Options

Default Values

This complete config object shows all possible config options in their default form. Do not change the default unless you are required to.

Here is a complete client configuration object utilizing all available fields:

1let clientConfig =
2 { "mobileKey": "YOUR_MOBILE_KEY",
3 "baseUri": "https://app.launchdarkly.com",
4 "streamUri": "https://clientstream.launchdarkly.com",
5 "eventsUri": "https://mobile.launchdarkly.com",
6 "eventsCapacity": 200,
7 "eventsFlushIntervalMillis": 5000,
8 "connectionTimeoutMillis": 3000,
9 "pollingIntervalMillis": 4000,
10 "backgroundPollingIntervalMillis": 6000,
11 "useReport": false,
12 "stream": true,
13 "disableBackgroundUpdating": false,
14 "offline": false,
15 "debugMode": true,
16 "evaluationReasons": false
17 };

User Configuration Options

Here is a complete user configuration object utilizing all available fields:

1let userConfig =
2 { key: '2fbfa269b78e24c8e967f482b89c939b',
3 name: 'grace_hopper',
4 firstName: 'Grace',
5 lastName: 'Hopper',
6 email: 'gracehopper@example.net',
7 anonymous: false,
8 privateAttributeNames: ['name'],
9 country: 'USA',
10 custom: {'groups': 'users'}
11 };

Let's walk through this code. The first key in the object is the user's key. In this case we've used the value 2fbfa269b78e24c8e967f482b89c939b. The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use any value such as a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other keys (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on the LaunchDarkly application dashboard, meaning that you can start segmenting and targeting users with these attributes.

In addition to built-in attributes like names and e-mail addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above. Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, andaccount plans. Anything you pass to us becomes available instantly on your dashboard.

Private attributes allow you to specify keys you do not want to be sent to the LaunchDarkly servers. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly. When this user is sent back to LaunchDarkly, the name attribute will be removed.

The anonymous key allows you to distinguish logged out or unregistered users while still using LaunchDarkly. Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly.

Variations

The variation method determines whether a flag is enabled or not for a specific user. In React Native, there is a variation method for each type (e.g. boolVariation, stringVariation):

1let jsonResult = await client.jsonVariation('MY_JSON_FLAG_KEY', {});

Variation calls take the feature flag key and a fallback value.

The fallback value will only be returned if an error is encountered. For example, the default value returns if the feature flag key doesn't exist or the user doesn't have a key specified.

The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn't exist already. There's no need to create users ahead of time (but if you do need to, take a look at identify).

Handling flag values on initial application launch
When LDClient is initialized for the first time at app launch, users will receive feature flag fallback values until an initial connection to LaunchDarkly is completed for the first time. Take a look at the section above on various ways to initialize the client.

VariationDetail

Availability
Since v2.1.0

The variationDetail methods work the same as variation, but also provide additional reason information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine the reason data programmatically; you can also view it with data export, if you are capturing detailed analytics events for this flag.

For more information, see Evaluation reasons.

All Flags

Creating Users

Unlike variation and identify calls, allFlags does not send events to LaunchDarkly. When you use allFlags, users are not created or updated in the LaunchDarkly dashboard.

The allFlags method returns an object containing flag keys and values. You may also register a listener that will fire when any flag in your environment changes.

1let allFlagsResult = client.allFlags();
2allFlagsResult.then(values => {
3 console.log(values);
4});
5
6// All Flags Listener
7let listenerId = "ARBITRARY_VALUE"
8let listener = value => Alert.alert('All Flags Listener Callback', value);
9client.registerAllFlagsListener(listenerId, listener);

Track

The track method allows you to record actions your users take in your app. In the LaunchDarkly dashboard, you can tie these events to goals in A/B tests. You can also attach custom JSON data to your event by passing an extra parameter to track. Here's a simple example:

Availability
Since v2.1.0

You can now optionally add a metricValue parameter to the track method if you are using the latest version of Experimentation.

1client.track('MY_GOAL_FLAG_KEY', false);
2client.track('MY_GOAL_FLAG_KEY_WITH_DATA', {'some_data':'value'});

Offline Mode

In some situations, you might want to stop making remote calls to LaunchDarkly and switch to the last known values for your feature flags. Offline mode lets you do this easily.

1let offlineResult = client.setOffline(); //true or false
2let offlineStatus = client.isOffline(); //true or false
3let onlineResult = client.setOnline(); //true or false
Lack of Network Connectivity

If a user's device is in airplane/flight mode or if they are not connected to a network, LaunchDarkly will use the latest stored flag settings in memory. If there are no previously stored flag settings, then the fallback values will be used.

Flush

Internally, the LaunchDarkly SDK keeps an event buffer for track calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a simulator), you may want to manually call flush to process events immediately.

1client.flush();

Identify

If your app is used by multiple users on a single device, you may want to change users and have separate flag settings for each user. To achieve this, the SDK will store the last 5 user contexts on a single device, with support for switching between different user contexts.

You can use the identify method to switch user contexts:

1let user = {'key': 'minimal_user'};
2await client.identify(user); //promise resolves to nil/null
3Alert.alert('identify', 'success');

The identify call will load any saved flag values for the new user and immediately trigger an update of the latest flags from LaunchDarkly.

Real-time Updates

LaunchDarkly manages all flags for a user context in real-time by updating flags based on a real-time event stream. When a flag is modified from the LaunchDarkly dashboard, the flag values for the current user will update almost immediately.

To accomplish real-time updates, LaunchDarkly broadcasts an event stream that is listened to by the React Native SDK. Whenever an event is performed on the dashboard, the React Native SDK is notified of the updated flag settings in real-time.

To perform real-time updates in your app, your app will need to register listeners for each flag you'd like to watch:

1if (this.state.listeners.hasOwnProperty(key)) {
2 return;
3}
4let listener = value => Alert.alert('Listener Callback', value);
5client.registerFeatureFlagListener('MY_LISTEN_FLAG_KEY', listener);
6this.setState({listeners: {...this.state.listeners, ...{['MY_LISTEN_FLAG_KEY']: listener}}});

Similarly you can unregister listeners to disable them:

1this.state.ldClient.unregisterFeatureFlagListener('MY_LISTEN_FLAG_KEY', this.state.listeners['MY_LISTEN_FLAG_KEY']);
2let {['MY_LISTEN_FLAG_KEY']: omit, ...newListeners} = this.state.listeners;
3this.setState({listeners: newListeners});

Background Fetch

The React Native SDK defaults to the background fetch behavior for the platform it's running on.

Monitoring SDK Status

The React Native SDK exposes some of its internal status through the Connection Status API to allow your application to monitor the SDK's status. This is provided primarily as a mechanism for the application to determine how recently the internal flag cache has been updated with the most recent values, as well as diagnosing potential reasons for the flag cache to be out of date. Please see the documentation for iOS or Android Connection Status for detailed explanation of the information available on that platform.

1let connectionInformation = client.getConnectionInformation();
2console.log("Connection Information: " + connectionInformation);

Data collection

To learn more about data collection within this SDK and implications on submissions to the Apple App Store, read Apple App Store data collection policy.