Skip to content

Instantly share code, notes, and snippets.

@carlesandres
Last active November 3, 2021 10:41
Show Gist options
  • Save carlesandres/17a87639da4244a6ef680ab2bb19929e to your computer and use it in GitHub Desktop.
Save carlesandres/17a87639da4244a6ef680ab2bb19929e to your computer and use it in GitHub Desktop.
LaunchDarkly React example
import { withLDConsumer } from 'launchdarkly-react-client-sdk';
const ConsumingComponent = (props) => {
// A `flags` object has been added to the `props`, which is updated with the value of the flags for the currently identified user
// An `ldClient` prop is also added which can be used to interact with Launchdarkly's client side SDK
const { flags, ldClient } = props;
// ldClient needs to be used to identify the user
useEffect( () => {
const identify = async(userObj) => {
ldClient.identify(userObj)
}
const userObj = createLDUserObjFromUserInfo(userInfo)
identify(userObj)
}, [userInfo, ldClient])
}
export default withLDConsumer()(ConsumingComponent);
import Cookies from 'js-cookie';
import { withLDProvider } from 'launchdarkly-react-client-sdk';
import { LD_IDENTIFIER_COOKIE_NAME } from 'lib/app-constants';
const activeFlags = {
'show-that-thing': false,
'value-of-that-experiment': 'some string'
};
const clientSideID = process.env.NEXT_PUBLIC_LAUNCHDARKLY_CLIENT_SIDE_ID;
// IMPORTANT!! This function is synchronous and it needs to remain synchronous.
//
// Please, do not attempt to be too clever about it. The way to make it
// wait for the user information before actually fetching the feature
// flags is by using the `deferInitialization` mechanism.
// See https://docs.launchdarkly.com/sdk/client-side/react/react-web#configuring-the-react-sdk
const LaunchDarklyProvider = (App) => {
const key = Cookies.get(LD_IDENTIFIER_COOKIE_NAME);
const user = key ? { key } : undefined;
return withLDProvider({
clientSideID,
user,
options: {
bootstrap: 'localStorage',
},
deferInitialization: false,
flags: activeFlags,
})(App);
};
export default LaunchDarklyProvider;
import LaunchDarklyProvider from 'lib/LaunchDarklyProvider';
const WrappingComponent = () => {
return (
<div>
// ...nested components
</div>
);
};
export LaunchDarkly(WrappingComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment