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.