'How to make useEffect listening to any change in localStorage?
I am trying to have my React app getting the todos array of objects from the localStorage and give it to setTodos. To do that I need to have a useEffect that listen to any change that occurs in the local storage so this is what I did:
useEffect(() => {
if(localStorage.getItem('todos')) {
const todos = JSON.parse(localStorage.getItem('todos'))
setTodos(todos);
}
}, [ window.addEventListener('storage', () => {})]);
The problem is that useEffect is not triggered each time I add or remove something from the localStorage. Is this the wrong way to have useEffect listening to the localStorage?
I tried the solution explained here but it doesn't work for me and I sincerely I do not understand why it should work because the listener is not passed as a second parameter inside the useEffect
Solution 1:[1]
You can't re-run the useEffect
callback that way, but you can set up an event handler and have it re-load the todos
, see comments:
useEffect(() => {
// Load the todos on mount
const todosString = localStorage.getItem("todos");
if (todosString) {
const todos = JSON.parse(todosString);
setTodos(todos);
}
// Respond to the `storage` event
function storageEventHandler(event) {
if (event.key === "todos") {
const todos = JSON.parse(event.newValue);
setTodos(todos);
}
}
// Hook up the event handler
window.addEventListener("storage", storageEventHandler);
return () => {
// Remove the handler when the component unmounts
window.removeEventListener("storage", storageEventHandler);
};
}, []);
Beware that the storage
event only occurs when the storage is changed by code in a different window to the current one. If you change the todos
in the same window, you have to trigger this manually.
Solution 2:[2]
const [todos, setTodos] = useState();
useEffect(() => {
setCollapsed(JSON.parse(localStorage.getItem('todos')));
}, [localStorage.getItem('todos')]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | T.J. Crowder |
Solution 2 | Fateme Norouzi |