Home > Net >  localStorage removing elements in array after browser refresh
localStorage removing elements in array after browser refresh

Time:11-25

I have a react app and I want to persist the array of favorites when the page refreshes.

The data is set correctly, I can see it in the dev tools. But when i refresh the page, the data is removed. Any ideas why this may be?

Link to sandbox - https://codesandbox.io/s/sad-surf-sqgo0q?file=/src/App.js:368-378

const App = () => {
  const [favourites, setFavourites] = useState([]);

  useEffect(() => {
    localStorage.setItem("favourites", JSON.stringify(favourites));
  }, [favourites]);

  useEffect(() => {
    const favourites = JSON.parse(localStorage.getItem("favourites"));
    if (favourites) {
      setFavourites(favourites);
    }
  }, []);

  return (
    <FavContext.Provider value={{ favourites, setFavourites }}>
      <HashRouter>
        <Routes>
          <Route path={"/"} element={<Dashboard />} />
          <Route path={"/favorites"} element={<Favorites />} />
        </Routes>
      </HashRouter>
    </FavContext.Provider>
  );
};

export default App;

CodePudding user response:

Make sure to set item if array is not empty

 useEffect(() => {
    if(favourites.length) localStorage.setItem("favourites", JSON.stringify(favourites));
  }, [favourites]);

CodePudding user response:

Yes, it is because when you reload the app the useEffect will trigger and you have an empty array in your favorite for the first time so it set the empty array in local storage. You can fix it by adding a simple check

  useEffect(() => {
    if(favourites.length > 0){
      localStorage.setItem("favourites", JSON.stringify(favourites));
    }
  }, [favourites]);

By this setItem only work when there is something in the favorites state

  • Related