简体   繁体   中英

Trying to build an eventlistener for localStorage with useEffect

I'm trying to implement an eventlistener that triggers an useEffect-function to render a shopping bag. At the moment the shopping bag only appears after reloading the page. This should happen instantly instead. I've build a sandbox for my problem: https://codesandbox.io/s/vigilant-oskar-drsvy?file=/src/App.js . When clicking the "Click it" button nothing appears but when reloading the page.

Here is also the code:

export default function App() {
  const [storageData, setStorageData] = useState(localStorage.getItem("alert"));

  useEffect(() => {
    setStorageData(localStorage.getItem("alert"));
  }, []);

  //insert eventlistener to dependency array of useEffect

  return (
    <div className="App">
      <button
        onClick={() => {
          localStorage.setItem("alert", "ShoppingBag");
        }}
      >
        click it
      </button>
      <div>{storageData}</div>
    </div>
  );
}

You need to kind of inverse how you are doing it - when you storageData changes, you should do localStorage.setItem , and then you do setStorageData and your useEffect will pick up the change and save it.

https://codesandbox.io/s/naughty-herschel-469i1

 import { useEffect, useState } from "react"; import "./styles.css"; export default function App() { const [storageData, setStorageData] = useState(localStorage.getItem("alert")); useEffect(() => { localStorage.setItem("alert", storageData); }, [storageData]); //insert eventlistener to dependency array of useEffect return ( <div className="App"> <button onClick={() => { setStorageData("ShoppingBag"); }} > click it </button> <div>{storageData}</div> </div> ); }

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