React Native WebSocket Disconnect Great
// eventHandlers.ts
export const useConnectionPauseHandler(
state: IGameData,
dispatch: React.Dispatch<any>
) => {
const [connectFn, setConnectFn] = useState<ConnectFN>(
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]);
Puzzled Puffin