简体   繁体   中英

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

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.

const [todos, setTodos] = useState();

useEffect(() => {
  setCollapsed(JSON.parse(localStorage.getItem('todos')));
}, [localStorage.getItem('todos')]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM