Skip to content

Instantly share code, notes, and snippets.

@ChrisLTD
Last active July 25, 2022 16:32
Show Gist options
  • Save ChrisLTD/72f2a51e7539069d9ab16c4a34bf721b to your computer and use it in GitHub Desktop.
Save ChrisLTD/72f2a51e7539069d9ab16c4a34bf721b to your computer and use it in GitHub Desktop.
/*
Launch Darkly Context Provider using their JavaScript Client SDK
This component is used to provide the feature flags context to the rest of the app.
This is how you can use feature flags in your components:
1) Add your flag to the `Flags` constant in this file if it's not already there:
myFlag: { slug: 'my-flag', defaultValue: false },
2) In your component add this import:
import { FeatureFlagsContext, Flags } from 'common/FeatureFlagsContext'
3) Load the context, and ask for the flag value:
const featureFlags = useContext(FeatureFlagsContext)
const isMyFlagEnabled = featureFlags.getFlagValue(Flags.myFlag)
The loading variable is exposed by the context to specifically cause re-renders when the state changes. Otherwise, the
component using the context might not pickup the proper flag value from the fully loaded LaunchDarkly client.
*/
/* eslint-disable sort-keys -- slug before default value */
import * as ld from 'launchdarkly-js-client-sdk'
import { createContext, memo, ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { LDClient } from 'launchdarkly-js-client-sdk'
import { userToFullName } from 'helpers'
type Flag = {
slug: string
defaultValue: boolean
}
export const Flags: {[key: string]: Flag } = {
myFlag: { slug: 'my-flag', defaultValue: false },
}
export type ContextValue = {
getFlagValue: (flag: Flag) => boolean
loading: boolean
}
export const FeatureFlagsContext = createContext<ContextValue>({
getFlagValue: () => false,
loading : true,
})
export const FeatureFlagsContextProvider = memo((props: { children: ReactNode }) => {
const [client, setClient] = useState<LDClient>()
const [loading, setLoading] = useState(true)
const getFlagValue = useCallback((flag: Flag): boolean => {
if (client) {
return client.variation(flag.slug, flag.defaultValue)
}
return flag.defaultValue
}, [client])
useEffect(() => {
if (loading) {
const ldUser: ld.LDUser = {
anonymous: true,
}
const options: ld.LDOptions = {
bootstrap: 'localStorage',
}
const ldClient = ld.initialize(MY_LAUNCH_DARKLY_CLIENT_ID, ldUser, options)
ldClient.waitUntilReady().then(() => {
console.log('FeatureFlagsContextProvider: ldClient initialized')
setClient(ldClient)
setLoading(false)
})
}
}, [loading])
const value = useMemo<ContextValue>(() => {
return {
getFlagValue,
loading,
}
}, [getFlagValue, loading])
return <FeatureFlagsContext.Provider value={value}>
{props.children}
</FeatureFlagsContext.Provider>
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment