react-amplitude
react-amplitude copied to clipboard
Support for changing userId in AmplitudeProvider after mounting
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.
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
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>