AutoSaveSession.jsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import React from "react";
  2. import { useRecoilValue } from "recoil";
  3. import { useC2C } from "react-sync-board";
  4. import { MessagesAtom } from "../components/message/useMessage";
  5. import useTimeout from "../hooks/useTimeout";
  6. import useSession from "../hooks/useSession";
  7. import debounce from "lodash.debounce";
  8. import {
  9. AvailableItemListAtom,
  10. BoardConfigAtom,
  11. AllItemsSelector,
  12. } from "../components/board";
  13. const GRACE_DELAY = import.meta.env.VITE_CI ? 100 : 5000;
  14. export const AutoSaveSession = () => {
  15. const { isMaster } = useC2C("board");
  16. const { saveSession } = useSession();
  17. // Delay the first update to avoid too many session
  18. const readyRef = React.useRef(false);
  19. useTimeout(() => {
  20. readyRef.current = true;
  21. }, GRACE_DELAY);
  22. const messages = useRecoilValue(MessagesAtom);
  23. const itemList = useRecoilValue(AllItemsSelector);
  24. const boardConfig = useRecoilValue(BoardConfigAtom);
  25. const availableItemList = useRecoilValue(AvailableItemListAtom);
  26. // eslint-disable-next-line react-hooks/exhaustive-deps
  27. const autoSave = React.useCallback(debounce(saveSession, 1000), [
  28. saveSession,
  29. ]);
  30. React.useEffect(() => {
  31. if (isMaster && readyRef.current) {
  32. autoSave();
  33. }
  34. }, [isMaster, autoSave, itemList, boardConfig, availableItemList, messages]);
  35. return null;
  36. };
  37. export default AutoSaveSession;