Skip to content
This repository has been archived by the owner on Mar 30, 2023. It is now read-only.

Support for changing userId in AmplitudeProvider after mounting #20

Open
gatlanticus opened this issue Sep 10, 2019 · 2 comments
Open

Comments

@gatlanticus
Copy link

I'm using AmplitudeProvider in the top level component of my SPA (see example).

Since this is the top-level component, it doesn't re-render when users log in and out. Instead, only the value of this.state.userId changes. However, userId of my amplitude instance does not change accordingly.

class App extends React.Component {
  render(){
    return(
      <AmplitudeProvider
        amplitudeInstance = amplitude.getInstance();
        apiKey = MY_API_KEY;
        userId = {this.state.userId};  //amplitude doesn't respond to changes in this.state.userId
      >
        <MyComponent>
          //my actual app            
        </MyComponent>
      </AmplitudeProvider>
    );
  }
}

I've discovered that the problem is because AmplitudeProvider only uses the userId prop in ComponentWillMount and then never looks at it again, even if it changes.

My solution has been to make a new amplitude instance in ComponentDidUpdate with the correct userId every time this.state.userId changes and pass that through. However, I think this work should be done in AmplitudeProvider instead, since the component is meant to be at the top of the tree where such things (i.e. logging in and out) are likely to happen.

@m-deacon
Copy link

Any update on adding this? It's quite vital that when users log out it changes the userId to anonymous and on a new user sign in it updates to that user. Or is that possible with the current set up and I'm just missing something.

@ryanashcraft

@sangsta
Copy link

sangsta commented Feb 22, 2021

My hack around this is to provide a key to AmplitudeProvider so that it'll create a new instance every time.

<AmplitudeProvider
  {...amplitudeProps}
  userId={userId}
  key={userId ?? 'no-user'}
>
  ...
</AmplitudeProvider>

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants