Skip to content

Instantly share code, notes, and snippets.

@vishalnarkhede
Last active January 22, 2021 13:16
Show Gist options
  • Save vishalnarkhede/f85e3e62305de229bc123846e0377115 to your computer and use it in GitHub Desktop.
Save vishalnarkhede/f85e3e62305de229bc123846e0377115 to your computer and use it in GitHub Desktop.
Right way to connect to chat
// If you are running into following error, then please use this gist as an example for implementing chat in react or RN
// "Watch or Presence requires an active websocket connection, please make sure to include your websocket connection_id"
// This error occurs if you make api call which requires active websocket connection (established by `client.connectUser`),
// without waiting for client.connectUser call to finish.
import React, { useEffect, useState } from 'react';
import { StreamChat } from 'stream-chat';
import {
Chat,
Channel,
ChannelHeader,
ChannelList,
MessageInput,
MessageInputFlat,
MessageList,
Thread,
Window,
} from 'stream-chat-react';
import 'stream-chat-react/dist/css/index.css';
const filters = { type: 'messaging', example: 1 };
const options = { state: true, watch: true, presence: true };
const sort = {
cid: 1,
last_message_at: -1,
updated_at: -1,
};
const App = () => {
const [chatClient, setChatClient] = useState();
useEffect(() => {
let _chatClient;
const setUpClient = async () => {
_chatClient = new StreamChat('api_key');
// Wait for connectUser to finish, before rendering components
await _chatClient.connectUser({ id: 'user_id' }, 'userToken');
setChatClient(_chatClient);
}
setUpClient();
return () => {
_chatClient && _chatClient.disconnect();
}
}, [])
// Or you can show some loading indicator, until we are connecting to chat
if (!chatClient) return null;
return (
<Chat client={chatClient}>
<ChannelList
filters={filters}
sort={sort}
options={options}
/>
<Channel>
<Window>
<ChannelHeader />
<MessageList />
<MessageInput Input={MessageInputFlat} focus />
</Window>
<Thread />
</Channel>
</Chat>
)
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment