airboardgame/src/hooks/SubscribeSessionEvents.jsx
Jérémie Pardou-Piquemal ae9dba21ca
Add generator (#377)
* Refactor form factory to prepare child edition
* Generated item update works
* Exclude fields from edition for generator
* Add translation
2021-10-17 13:29:22 +02:00

47 行
1.2 KiB
JavaScript

import React from "react";
import { useWire, useBoardConfig } from "react-sync-board";
export const SubscribeSessionEvents = ({ getSession, setSession }) => {
const { wire, isMaster } = useWire("board");
const [, setBoardConfig] = useBoardConfig();
// Use ref to avoid too fast register and unregister
const getSessionRef = React.useRef(getSession);
getSessionRef.current = getSession;
// if first player register callback to allow other user to load game
React.useEffect(() => {
const unsub = [];
if (isMaster) {
wire
.register("getSession", async () => {
return await getSessionRef.current();
})
.then((unregister) => {
unsub.push(unregister);
});
}
return () => {
unsub.forEach((u) => u());
};
}, [wire, isMaster]);
// Subscribe loadSession and updateBoardConfig events
React.useEffect(() => {
const unsub = [];
unsub.push(
wire.subscribe("loadSession", (session) => {
setSession(session);
})
);
return () => {
unsub.forEach((u) => u());
};
}, [wire, setBoardConfig, setSession]);
return null;
};
export default SubscribeSessionEvents;