One of the most common reasons for an integration problem is a race condition between making an API request and successfully initializing the client.
Every API request from the client-side requires that the client is established and the TLS handshake is complete. Fortunately, our Edge network of servers makes this as fast as possible. However, it must be complete before further API requests are made.
An example error you may receive would be
"you can only set device before opening a web socket connection"
In the following example a state is declared called clientIsReady which is set to true only once the await chatClient.connectUser() function is called.
Then there is a check for !chatClient.userID (which is true when the client is successfully initialized) to ensure that the setupClient() function is executed.
Ensuring that the client is ready before performing subsequent API requests is always a good idea.
// useChatClient.js
import { useEffect, useState } from 'react';
import { StreamChat } from 'stream-chat';
import { chatApiKey, chatUserId, chatUserName, chatUserToken } from './chatConfig';
const user = {
id: chatUserId,
name: chatUserName,
};
const chatClient = StreamChat.getInstance(chatApiKey);
export const useChatClient = () => {
const [clientIsReady, setClientIsReady] = useState(false);
useEffect(() => {
const setupClient = async () => {
try {
await chatClient.connectUser(user, chatUserToken);
setClientIsReady(true);
} catch (error) {
if (error instanceof Error) {
console.error(`An error occurred while connecting the user: ${error.message}`);
}
}
};
if (!chatClient.userID) {
setupClient();
}
}, []);
return {
clientIsReady,
};
};
Comments
0 comments
Please sign in to leave a comment.