0

I'm developing my own project and have a simple problem which I can not solve easily.

So, I have a state like below

     const [state, setState] = useState({
        externalEvents: [],
      });

and I can update a state with a function like this

(state is saved in a localstorage too as you can see)

const addTodo = (e) => {
    e.preventDefault();
    if (title === "" || color === "") {
      alert("please type what to do or choose a color");
    } else {
      setState({
        externalEvents: [
          ...state.externalEvents,
          { title: title, color: color, custom: custom, id: uuidv4(), },
        ],
      },
      );
      localStorage.setItem('externalEvents',JSON.stringify(state.externalEvents))
      
     
    
      setTitle("");
      setCustom("");
    }
  };

but problem is my localstorage is delayed.

For instance. if I save 'A' to state, state woulbe like this

state:{externalEvents:[{A}]}

but localstorage only return empty array

localstorage

key              value
   externalEvents   []

so I added one more thing 'B' and it would be like this

state:{externalEvents:[{A},{B}]}

localstorage

  key              value
    externalEvents   [A]

it only update the past one and not the current one

Could you tell me why is my localstorage being dumb and lagged?(maybe I'm dumb) and also how can I solve this ridiculous? thx for reading, your help will be appreciated.

geo
  • 821
  • 1
  • 8
  • 15
  • 1
    localStorage is synchronous, so it can't lag. The issue here is that React state updates are enqueued and asynchronously processed, so your code is saving to localStorage the state value from the current render cycle, not what it will be updated to on a subsequent render cycle. Use an `useEffect` with a dependency on `state` to persist updates to localStorage when the state updates. – Drew Reese Sep 10 '21 at 23:51
  • @DrewReese I appreciate you a lot. Mr.Reese! you saved me this time again! – geo Sep 11 '21 at 00:02

0 Answers0