Home > OS >  How to synchronous useState with passing state to localstorage
How to synchronous useState with passing state to localstorage

Time:05-19

I ran into an asynchronous useState problem.

I have a situation where I first need to add an object to the state array in the handler. And then add this state to the localStorage.

setFavoritedSongs ((prev) => [...prev, {name: "Lala", length: "3:20"}]);

localStorage.setItem("storageItemName", JSON.stringify(favoritedSongs));

If I delete the entire localStorage first and run the handler. So an empty array is added to my localStorage (the state shows me updated). After the action again, the required object is finally added to my array.

I tried something like this, but still the same problem.

const tempArray = favoritedSongs.push({ name: "Lala", length: "3:20" });

localStorage.setItem(storageItemName, JSON.stringify(tempArray));

How do you solve this, please?

/// EDIT

I have something like this

const FavoriteSong = () => {
  const song = { id: 1, name: "Lala", length: "3:20" };
  const [favoritedSongs, setFavoritedSongs] = useState([]);
  const [isFavorited, setIsFavorited] = useState(false);

  useEffect(() => {
    if (localStorage.getItem("storageItemName")) {
      const storageSongs = JSON.parse(
        localStorage.getItem("storageItemName") || ""
      );
      setFavoritedSongs(storageSongs);

      const foundSong = storageSongs?.find((song) => song.id === song.id);

      foundSong ? setIsFavorited(true) : setIsFavorited(false);
    }
  }, [song]);

  const handleClick = () => {
    if (isFavorited) {
      const filteredSong = favoritedSongs.filter(
        (song) => song.id !== song.id
      );
      localStorage.setItem("storageItemName", JSON.stringify(filteredSong));

      setIsFavorited(false);
    } else {
      setFavoritedSongs((prev) => [...prev, song]);

      localStorage.setItem("storageItemName", JSON.stringify(favoritedSongs));
      setIsFavorited(true);
    }
  };

  return <div onClick={handleClick}>CLICK</div>;
};

export default FavoriteSong;

CodePudding user response:

Just place your localStorage.set logic inside a useEffect to make sure it runs after the state actually changes.

useEffect() => {
    localStorage.setItem(...);
}, [favoritedSongs]};

CodePudding user response:

For that you can Use the condition If data in the array then It will set in localStorage otherwise not

const tempArray = favoritedSongs.push({ name: "Lala", length: "3:20" });

tempArray.length && localStorage.setItem(storageItemName, JSON.stringify(tempArray));

.

setFavoritedSongs ((prev) => [...prev, {name: "Lala", length: "3:20"}]);

FavoritedSongs.length(your state name) && localStorage.setItem("storageItemName", JSON.stringify(favoritedSongs));
  • Related