SubscribeSessionEvents.jsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import React from "react";
  2. import useC2C from "./hooks/useC2C";
  3. import useBoardConfig from "./useBoardConfig";
  4. export const SubscribeSessionEvents = ({ getSession, setSession }) => {
  5. const { c2c, isMaster } = useC2C("board");
  6. const [, setBoardConfig] = useBoardConfig();
  7. // if first player register callback to allow other user to load game
  8. React.useEffect(() => {
  9. const unsub = [];
  10. if (isMaster) {
  11. c2c
  12. .register("getSession", async () => {
  13. return await getSession();
  14. })
  15. .then((unregister) => {
  16. unsub.push(unregister);
  17. });
  18. }
  19. return () => {
  20. unsub.forEach((u) => u());
  21. };
  22. }, [c2c, getSession, isMaster]);
  23. // Subscribe loadSession and updateBoardConfig events
  24. React.useEffect(() => {
  25. const unsub = [];
  26. unsub.push(
  27. c2c.subscribe("loadSession", (session) => {
  28. setSession(session);
  29. })
  30. );
  31. unsub.push(
  32. c2c.subscribe("updateBoardConfig", (newConfig) => {
  33. setBoardConfig(newConfig, false);
  34. })
  35. );
  36. return () => {
  37. unsub.forEach((u) => u());
  38. };
  39. }, [c2c, setBoardConfig, setSession]);
  40. return null;
  41. };
  42. export default SubscribeSessionEvents;