react native websocket disconnect handler

The solution for “react native websocket disconnect handler” can be found here. The following code will assist you in solving the problem.

// eventHandlers.ts
export const useConnectionPauseHandler(
state: IGameData,
dispatch: React.Dispatch
) => {
const [connectFn, setConnectFn] = useState(
null as unknown as ConnectFN
);

const disconnectCallback = useCallback(() => {
if (state.connectionStatus !== ConnectionLifecycle.RESUMED)
dispatch({ type: ‘DISCONNECTED’ });
}, [dispatch, state.connectionStatus]);

const pauseCallback = useCallback(() => {
if (…) {
// disconnection is expected, or an error is prevting the connection from reconnecting
console.log(‘expected disconnection’);
dispatch({ type: ‘DISCONNECTED’ });
} else if (…) {
// connection is unexpected, and not attempting reconnection
console.log(‘unexpected disconnection’);
dispatch(‘SESSION_PAUSED’);
if (connectFn) connectFn(state.gameCode!, null, state.playerId);
setTimeout(disconnectCallback, 30 * 1000);
}
}, [
disconnectCallback,
dispatch,
connectFn,
state.gameCode,
state.playerId,
state.connectionStatus,
state.gameStatus,
]);

const registerConnectFunction = useCallback((fn: ConnectFN) => {
setConnectFn(() => fn); // do this to avoid confusing the react dispatch function
}, []);

return [registerConnectFunction, pauseCallback];
}

// GameContextProvider.tsx
const [setConnectFn, onClose] = useConnectionPauseHandler(state, dispatch);
const [connect, sendMessage] = useSession(
onOpen,
onMessage,
onClose
);

useEffect(() => {
console.log(‘wiring everything…’);
setConnectFn(connect);
}, [setConnectFn, connect]);

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

0
inline scripts encapsulated in