Skip to content

Switching Users #325

@justinmchase

Description

@justinmchase

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}
    />
  )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions