LaunchDarkly Developer Documentation

Get started in under 30 minutes.
LaunchDarkly provides feature flags as a service for Java · Python · Ruby · Go · Node.js · PHP · .NET. Control feature launches -- who sees what and when -- without multiple code deploys. Easy dashboard for phased rollouts, targeting and segmenting.
Need more help? write us at support@launchdarkly.com

Get Started    Documentation

React Native SDK Reference

SDK Version Compatibility

The SDK is currently only compatible with Xcode 10.1 and React Native 0.57.7

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-- head to our React Native SDK GitHub repository to look under the hood. Additionally you can clone and run a sample application using this SDK.

Getting Started

Expo Usage

The LaunchDarkly React Native Client SDK does not work with Expo because the SDK uses native module.

Building on top of our Quickstart 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.

npm install --save launchdarkly-react-native-client-sdk
react-native link launchdarkly-react-native-client-sdk

Add the following line to your app build.gradle before your dependencies.

configurations.all {exclude group: 'com.android.support', module: 'support-v4'}

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.1 or lower because it is compiled against Swift 3.

source 'https://github.com/CocoaPods/Specs.git'

use_frameworks!
platform :ios, '9.0'

target 'YOUR_MODULE_NAME' do
  rn_path = '../node_modules/react-native'
  rn_darkly_path = '../node_modules/launchdarkly-react-native-client-sdk/ios/'

  pod 'yoga', path: "#{rn_path}/ReactCommon/yoga/yoga.podspec"
  pod 'React', path: rn_path, subspecs: [
    'Core',
    'CxxBridge',
    'DevSupport',
    'RCTActionSheet',
    'RCTAnimation',
    'RCTGeolocation',
    'RCTImage',
    'RCTLinkingIOS',
    'RCTNetwork',
    'RCTSettings',
    'RCTText',
    'RCTVibration',
    'RCTWebSocket',
  ]

  # React Native third party dependencies podspecs
  pod 'DoubleConversion', :podspec => "#{rn_path}/third-party-podspecs/DoubleConversion.podspec"
  pod 'glog', :podspec => "#{rn_path}/third-party-podspecs/glog.podspec"
  pod 'Folly', :podspec => "#{rn_path}/third-party-podspecs/Folly.podspec"

  #launchdarkly-react-native-client-sdk dependencies

  pod 'LaunchDarkly', :git => 'https://github.com/launchdarkly/ios-client.git', :tag => '3.0.0-beta.3'
  
  pod 'LaunchdarklyReactNativeClient', path: rn_darkly_path

end

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:

import 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-- they can be safely exposed in your client-side code.

let client = new LDClient();

let clientConfig =
    { "mobileKey": "YOUR_MOBILE_KEY",
      "stream": true,
      "offline": false
    };

let userConfig = { "key": "user_key" };

client.configure(clientConfig, userConfig);

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

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

let clientConfig =
  { "mobileKey": "YOUR_MOBILE_KEY",
    "baseUri": "https://ld.launchdarkly.com",
    "streamUri": "https://stream.launchdarkly.com",
    "eventsUri": "https://events.launchdarkly.com",
    "eventsCapacity": 200,
    "eventsFlushIntervalMillis": 5000,
    "connectionTimeoutMillis": 3000,
    "pollingIntervalMillis": 4000,
    "backgroundPollingIntervalMillis": 6000,
    "useReport": false,
    "stream": true,
    "disableBackgroundUpdating": false,
    "offline": false,
    "debugMode": true
  };

User Configuration Options

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

let userConfig =
    { key: '2fbfa269b78e24c8e967f482b89c939b',
     	name: 'grace_hopper',
     	firstName: 'Grace', 
     	lastName: 'Hopper', 
     	email: 'gracehopper@example.net', 
     	isAnonymous: false, 
     	privateAttributeNames: ['name'], 
     	customAttributes: {'groups': 'users'}
    };
  

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-- organizations, groups, account 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 isAnonymous 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):

let jsonResult = 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, 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.

All Flags

Creating Users

Note that unlike variation and identify calls, allFlags does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard.

The allFlags method returns an object containing flag keys and values.

let allFlagsResult = client.allFlags();

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:

client.track('MY_GOAL_FLAG_KEY', false);
client.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.

let offlineResult = client.setOffline(); //true or false
let offlineStatus = client.isOffline(); //true or false
let 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.

client.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:

let user = {'key': 'minimal_user'};
await client.identify(user); //promise resolves to nil/null
Alert.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 via 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:

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

Similarly you can unregister listeners to disable them:

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

Background Fetch

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


React Native SDK Reference


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.