Error when switching users
I'm using version 2.5.0.
My app markup:
<Chat client={this.props.streamApi} theme={"messaging light"}>
<ChannelList filters={this.state.filters} sort={this.state.sort} />
<Channel>
<Window>
<ChannelHeader />
<MessageList />
<MessageInput />
</Window>
<Thread />
</Channel>
</Chat>
Which works fine.
Now if I attempt to switch to another user after the component has rendered via streamApi.setUser like this:
await this.props.streamApi.disconnect();
await this.props.streamApi.setUser({ id: user.streamUserId }, user.streamUserToken);
I get a connection error like this:

usePaginatedChannels.js:69 Error: Call setUser or setAnonymousUser before creating a channel
at StreamChat.channel (client.ts:1389)
at StreamChat._callee9$ (client.ts:1243)
at tryCatch (runtime.js:63)
at Generator.invoke [as _invoke] (runtime.js:293)
at Generator.next (runtime.js:118)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25)
How do I switch users within the chat?
gz#6252
From my initial investigation it looks like the error is caused by the usePaginatedChannels hook that runs between calls to
await this.props.streamApi.disconnect();
and
await this.props.streamApi.setUser({ id: user.streamUserId }, user.streamUserToken);
At the same time, stream chat API will not let me setUser without calling disconnect first.
Agent comment from Stephen Hodgetts in Zendesk ticket #6252:
Hello, switching users in the middle of running the app isn't recommended. The client that you are disconnecting runs through the entire Stream code, and you're disrupting it. You'll need to unmount all of the components, disconnect, set the user, then re-mount.
Is there an example of how exactly I can do that?
@agaace Sorry for getting back to you a bit late. Switching user is out of the scope of the library, but you can easily achieve it by unmounting the Chat app and mounting it again using a new StreamChat instance. Hopefully this code snippet will help you:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { chatClient: new StreamChat('YOUR_KEY') };
}
async changeUser(userId, userToken) {
const oldClient = this.state.chatClient;
await this.setState({ chatClient: null }); // IMPORTANT to have a clean unmount
oldClient.disconnect(); // IMPORTANT to disconnect previous client to reduce your app usage
const chatClient = new StreamChat('YOUR_KEY');
chatClient.setUser({ id: userId }, userToken);
return this.setState({ chatClient });
}
render() {
if (!this.state.chatClient) return null; // You can render a custom UI loading here
return (
<Chat client={this.state.chatClient}>{/* YOUR CHAT COMPONENETS */}</Chat>
);
}
}
closing this for housekeeping. In case you still have this issue, please let us know to reopen it.