Home > database >  Updating local storage in React after filtering the array
Updating local storage in React after filtering the array

Time:01-31

I try to filter my array with items, that was previously received from Local Storage. After filtering the array I try to update the local storage, but the app crashes. What's the correct way to address local storage after changing state? PS If I just filter the array, items are still in Local Storage and I need to update it somehow.

Here is the full code: https://codesandbox.io/s/movie-app-v4-97dw37?file=/src/Watchlist.js

export default function Watchlist() {
  const [savedData, setSavedData] = useState(
    JSON.parse(localStorage.getItem("watchListData"))
  );
  // console.log(savedData);

  function remove(id) {
    console.log("removed", id);
    setSavedData((prevSavedData) =>
      prevSavedData.filter((movie) => movie.id !== id)
    );
  }
// useEffect(() => {
  //   localStorage.setItem("watchListData", JSON.stringify(savedData));
  // }, [savedData]);

CodePudding user response:

Edited Answer

You must have just changed the code in the sandbox, because now it's formatted incorrectly, and I'm seeing the same error in your comment.

You can't put a useEffect within another handler function like you have here:

function remove(id) {
  console.log("removed", id);
  setSavedData((prevSavedData) =>
    prevSavedData.filter((movie) => movie.id !== id)
    useEffect(() => {
      localStorage.setItem("watchListData", JSON.stringify(savedData));
    }, [savedData]);
  );
}

You have to keep it at the root level of the function (or perform the .setItem action as a standalone call and not within a useEffect

  function remove(id) {
    console.log("removed", id);
    setSavedData((prevSavedData) =>
      prevSavedData.filter((movie) => movie.id !== id)
    );
  }

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

Original Answer

There doesn't seem to be anything crucial wrong with your code itself.

Minor fix

It looks like you're filtering on movie.id instead of movie.imdbID, so once you fix that...

prevSavedData.filter((movie) => movie.imdbID !== id)

It worked fine for me, adding and removing movies from the watch list.

Fix on your computer

My guess for why it may be crashing on your end is if you have an outdated or corrupted object saved to your local storage, that could mess with your app. Try clearing your localStorage and trying again.

Long term solution

I'd also recommend adding more error checking instead of just trusting that whatever is left in localStorage is safe and up-to-date.

  • Related