Home > Back-end >  how to solve the problem when the data from localStorage has been deleted when leaving crome there i
how to solve the problem when the data from localStorage has been deleted when leaving crome there i

Time:02-05

When I have deleted the bookmark data from localStorage and closed my website tab or closed Chrome when I visited my website again why is there still one data left which is the data I deleted most recently.

my code is like this

  const [bookmark, setBookmark] = useState([]);

  const addToBookmark = (ayatLs) => {
    setBookmark([...bookmark, ayatLs]);
  };

  const removeBookmark = (bookmarkToRemove) => {
    setBookmark(bookmark.filter((x) => x !== bookmarkToRemove));
  };

  useEffect(() => {
    if (bookmark.length === 0) return;
    localStorage.setItem('bookmark', JSON.stringify(bookmark));
  }, [bookmark]);

  useEffect(() => {
    const bookmarkFromLocalStorage = localStorage.getItem('bookmark');

    const parsedBookmark =
      bookmarkFromLocalStorage !== null
        ? JSON.parse(bookmarkFromLocalStorage)
        : [];

    setBookmark(parsedBookmark);
  }, []);

CodePudding user response:

Here you are setting the data in localstorage using the useEffect. Once the value is set in localstorage, it stays there till it's not deleted manually using localStorage.removeItem("key");. Here removing the value from bookmark won't work.

You need to use .removeItem('key') to do so. Doing this will remove the whole value from localstorage. So you have to re-store the values in localstorage.

CodePudding user response:

The problem is with your "update" useEffect.

If you remove an Item from you bookmark array, your code does the following:

Let's say you start off with two elements in your bookmark array, so:


bookmark.length === 2 localStorage has two items in it,

then you run removeBookmark, the array get's copied with just one element,

the first useEffect gets triggered by the updated bookmark variable, and the new array (with length 1, right) gets written to localStorage.


Now bookmark.length === 1, and you run removeBookmark again.

The bookmark array is now empty, so bookmark.length === 0, so the if-statement if (bookmark.length === 0) return; makes it so there are no more changes to your localStorage, thus the last item is never removed, and there is still one item in your localStorage array.


If you change the useEffect to just this:

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

There should just be an empty array in your localStorage when you remove the last item.

  • Related