Delay websocket connection with react-use-websocket

Viewed 16

I have a component that uses react-use-websocket to instantiate a websocket. The socket needs authentication and since I can't use headers to pass the token, I need to pass it in the query parameters.

However, the initial websocket connection fails, because the token is not yet provided. After the initial connection times out, it attempts to reconnect, this time with the correct access token.

Is there a way to delay the initial connection until the token is populated/updated? The token is stored in the redux state.

const accessToken = useSelector(state => state.auth.access.token);

const getSocketURL = useCallback(() => {
    let url = new URL(`ws://${window.location.hostname}:8001/ws/commands`);
    if (accessToken) url.searchParams.append('token', accessToken);
    console.log('URL', `${url}`);
    return `${url}`;
}, []);

const { readyState, getWebSocket } = useWebSocket(getSocketURL, {
    share: true,
    retryOnError: true,
    shouldReconnect: (e) => true,
    reconnectInterval: 4,
    reconnectAttempts: 2,
    onError: (e) => console.error('Error in websocket', e)
});
1 Answers

From the Documentation it seems that useWebSocket accepts a third argument shouldConnectthat defaults to true.

So setting it to false when there is no token should work:

const { readyState, getWebSocket } = useWebSocket(getSocketURL, {
    share: true,
    retryOnError: true,
    shouldReconnect: (e) => true,
    reconnectInterval: 4,
    reconnectAttempts: 2,
    onError: (e) => console.error('Error in websocket', e)
}, 
   Boolean(accessToken)
);
Related