root.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import React, { useCallback, useState } from 'react';
  2. import { useReducer } from 'reinspect';
  3. import { nameSet } from '../actions';
  4. import { DispatchContext, StateContext } from '../context/state';
  5. import { useDispatchWithEffects, useOnMessage, useSocket } from '../hooks/socket';
  6. import { globalReducer, initialState } from '../reducer';
  7. import { init } from '../utils/state';
  8. import { App } from './app';
  9. import { Identify } from './identify';
  10. export const Root: React.FC = () => {
  11. const [state, dispatch] = useReducer(globalReducer, initialState, init, 'global');
  12. const onMessage = useOnMessage(dispatch);
  13. const onLogin = useCallback(
  14. (name: string): void => {
  15. dispatch(nameSet(name));
  16. },
  17. [dispatch],
  18. );
  19. const { name, onIdentify, socket, connecting, connected, error } = useSocket(onMessage, onLogin);
  20. const dispatchWithEffects = useDispatchWithEffects(state, dispatch, socket);
  21. const [interacted, setInteracted] = useState<boolean>(false);
  22. if (!(socket && connected && name) || error) {
  23. return (
  24. <Identify connecting={connecting} onIdentify={onIdentify} setInteracted={setInteracted} />
  25. );
  26. }
  27. return (
  28. <StateContext.Provider value={state}>
  29. <DispatchContext.Provider value={dispatchWithEffects}>
  30. <App socket={socket} interacted={interacted} setInteracted={setInteracted} />
  31. </DispatchContext.Provider>
  32. </StateContext.Provider>
  33. );
  34. };