2021年4月2日星期五

React functions not happening in order

The problem I'm having is that this set of code NEEDS to happen in order. It is all packaged inside a component that is updating every second. I need to set a timestamp every second. BUT when I load the page, I want to get the timestamp from local storage BEFORE the component updates local storage and changes the time stamp. I'm using React and a library called Lockr that just makes it easier to manipulate local storage.

Here's a video of the app I'm working with and the component that's updating every second to provide context to my issue. I highlight my console log being 0. This is the issue I want to fix. I need the console log to not give me 0, but the current timestamp - the previous timestamp. This is so if a user using my app goes offline and comes back, it counts the time they were gone.: https://www.youtube.com/watch?v=N0tOZhHfio4

Here's my current code:

  const exampleComponent = () => {      const d = new Date() /1000        const timeStamp = () => {      return Math.round(d)    }      const idler = () => {      return timeStamp() - Lockr.get('timeStamp')    }        window.onload = (event) => {       console.log(idler())    }    Lockr.set('timeStamp', timeStamp());        useEffect(() => {  const timer = setInterval(() => {  setState((state) => ({    minions: state.minions,    counter: state.counter + state.minions + (state.minionSupervisors*3) + (state.minionManagers * 9) +     (state.grandmas * 18) +     (state.dads * 36) +     (state.aliens * 72) +    (state.angels * 144),    minionSupervisors: state.minionSupervisors,    minionManagers: state.minionManagers,    grandmas: state.grandmas,    dads: state.dads,    aliens: state.aliens,    angels: state.angels,  }));    }, 1000);        return () => {      clearInterval(timer);    };    // eslint-disable-next-line  },[]);  }             
https://stackoverflow.com/questions/66926702/react-functions-not-happening-in-order April 03, 2021 at 08:32AM

没有评论:

发表评论