Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switching Users #325

Open
justinmchase opened this issue Nov 15, 2024 · 0 comments
Open

Switching Users #325

justinmchase opened this issue Nov 15, 2024 · 0 comments

Comments

@justinmchase
Copy link

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'

export const FeatureFlagsProvider: React.FC<PropsWithChildren> = ({ children }) => {
  const ldProvider = useRef<LDProvider>(null)
  const { user } = useContext(AuthContext)

  const clientSideID = 'your-client-side-id'

  const context: LDContext = user
    ? {
        kind: 'user',
        key: user.id,
        name: user.name,
        email: user.email,
        anonymous: false,
        custom: {
          roles: user.roles ?? [],
        },
      }
    : { kind: 'user', anonymous: true }

  useEffect(() => {
    const effect = async () => {
      console.debug('switching ld context', context, ldProvider)

      // this switches the user in the providers client
      await ldProvider.current?.state.ldClient?.identify(context)

      // Update the provider
      ldProvider.current?.forceUpdate()
    }
    effect()
  }, [user])

  return (
    <LDProvider
      clientSideID={clientSideID}
      context={context}
      children={children}
      ref={ldProvider}
    />
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant