react-amplitude icon indicating copy to clipboard operation
react-amplitude copied to clipboard

Support for changing userId in AmplitudeProvider after mounting

Open gatlanticus opened this issue 5 years ago • 2 comments

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.

gatlanticus avatar Sep 10 '19 05:09 gatlanticus

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

m-deacon avatar Oct 10 '19 10:10 m-deacon

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>

sangsta avatar Feb 22 '21 22:02 sangsta