DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Renan Monteiro
Renan Monteiro

Posted on

Save state to localStorage

Good morning,

I need to save a state (which is a list of objects) in a localStorage, but the first value is always "[]", because I initialized the state that way.

const [favorites, setFavorites] = useState<IPodcast[]>([]);
Enter fullscreen mode Exit fullscreen mode

On localStorage it looks like this:
Image description

I need the first value saved in localStorage to be the first value in my list. Below is the code responsible for saving the state in localStorage.

function adicionarFavorito(evento: React.FormEvent<HTMLFormElement>) {
evento.preventDefault();
podcastList.filter((p) => p.id === idPodcast)
.map((p) => (setFavorites((oldFavorites) => [...oldFavorites, { ...podcastList[p.num] }])));
localStorage.setItem("favorites", JSON.stringify(favorites));
}
Enter fullscreen mode Exit fullscreen mode

Can someone help me?

Top comments (0)

πŸ” If you came here from Google, why not take a look at some of our top posts?