You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I wanted to file this issue for anyone, including my future self, who tries to use this library (as of version 3.6.0) and struggles with switching users.
There are two basic issues that my solution solves pretty simply, one is during initialization going from anonymous to non-anonymous user as the context becomes available and then later as you're just switching users during the course of the app running.
The general solution is to use the ref field on the provider to to get access to the correct ldClient that the provider is using, then to forcefully re-initialize on context switch.
import{PropsWithChildren,useContext,useEffect,useRef}from'react'import{LDContext,LDProvider,initialize}from'launchdarkly-react-client-sdk'import{AuthContext}from'../auth/AuthProvider'exportconstFeatureFlagsProvider: React.FC<PropsWithChildren>=({ children })=>{constldProvider=useRef<LDProvider>(null)const{ user }=useContext(AuthContext)constclientSideID='your-client-side-id'constcontext: LDContext=user
? {kind: 'user',key: user.id,name: user.name,email: user.email,anonymous: false,custom: {roles: user.roles??[],},}
: {kind: 'user',anonymous: true}useEffect(()=>{consteffect=async()=>{console.debug('switching ld context',context,ldProvider)// this switches the user in the providers clientawaitldProvider.current?.state.ldClient?.identify(context)// Update the providerldProvider.current?.forceUpdate()}effect()},[user])return(<LDProviderclientSideID={clientSideID}context={context}children={children}ref={ldProvider}/>)}
The text was updated successfully, but these errors were encountered:
I wanted to file this issue for anyone, including my future self, who tries to use this library (as of version
3.6.0
) and struggles with switching users.There are two basic issues that my solution solves pretty simply, one is during initialization going from anonymous to non-anonymous user as the context becomes available and then later as you're just switching users during the course of the app running.
The general solution is to use the
ref
field on the provider to to get access to the correct ldClient that the provider is using, then to forcefully re-initialize on context switch.The text was updated successfully, but these errors were encountered: