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>) {
podcastList.filter((p) => === 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)