2 years ago
#379948
DeAssis Filho
React setState don't saving List of components that acess localStorage
My project is a Stopwatch written in typescript, using React and restore last session with the localStorage's browser. Detail of functionalities on the git repo README.md. The states stopwatches, restoredStopwatches and sessionRestored on src/Stopwatch/controller.tsx are not updating correcty on React's setSate().
Principally the restoredStopwatches state are not updating when using Stopwatch component on src/Stopwatch/index.tsx (Therefore this the restore of last sessions are not working fully, just set on stopwatch). I have tested with other test simple component and runned perfectly. The others states are not working on looking the chrome's debugger runnig.
Declaration of states (src/Stopwatch/controller.tsx)
  const [stopwatches, setStopwatches] = useState<JSX.Element[]>([]);
  const [restoredStopwatches, setRestoredStopwatches] = useState<JSX.Element[]>([]);
  const [sessionRestored, setSessionRestored] = useState<boolean>(false);
Use example of setState
  function restoreStopwatch(uuid: string) {
    const lastUnusedSessionsUUIDs = getLastUnusedSessionsUUIDs(
      getLastSessionsUUIDs()
    );
    if (
      lastUnusedSessionsUUIDs.find(
        (lastUnusedSessionUUID) => uuid === lastUnusedSessionUUID
      )
    ) {
      console.log(`not restored stopwatch, with uuid ${uuid}, not used`);
    } else {
      setRestoredStopwatches([
        ...restoredStopwatches,
        <Stopwatch key={uuid.slice(5, 8)} uuid={uuid} />,
      ]);
      console.log(`restored stopwatch, with uuid ${uuid}`);
    }
  }
I think that is because the Stopwatch access localStorage and the component is heavy to the setState run on correctly time (even being asynchronous).
I tried to moved code from src/App.tsx to src/components/Stopwatch/controller.tsx expecting turn less heavy the code, but not worked on.
reactjs
typescript
local-storage
react-state
0 Answers
Your Answer