SubscribeSessionEvents.jsx 1.2 KB

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