I have made a working example here: https://codesandbox.io/s/magical-flower-o0gyn?file=/src/App.js
When I click the hide button I want to save the updated data to localstorage:
- I click hide on first column:
setValueWithCallback
runs, sets the callback to a ref & sets the state useEffect
kicks in, calls the callback with the updated datasaveToLocalStorage
is called, in auseCallback
withdata
set as a dependency
The problem is at the 3rd step, what gets saved to localstorage is {visible: true}
for both.
I know if I change this line:
const saveToLocalStorage = useCallback(() => {
localStorage.setItem(
`_colProps`,
JSON.stringify(data.map((e) => ({ id: e.id, visible: e.visible })))
);
}, [data]);
To this:
const saveToLocalStorage = localStorage.setItem(
`_colProps`,
JSON.stringify(data.map((e) => ({ id: e.id, visible: e.visible })))
);
It works, but I cannot get my head around, why it does not with the first. I assume it must be some closure thing, but I don't see it.
If data
has already been updated, and useEffect
ran the callback, why it is not updated in the dependencies array?.
Yes, the example is weird and the 2nd solution is perfectly fine, I just wanted to demonstrate the problem.
Thanks for the help!