Next.js Discord

Discord Forum

LocalStorage with useState

Unanswered
Michele posted this in #help-forum
Open in Discord
Hi everyone, I need help with LocalStorage with hook useState

26 Replies

Great black wasp
Just use jotai
Is there some method from scratch?
Hi, I have an application where you can select favourite accounts. All these accounts are within a back-end and I show them via the .map method. I should be able to keep the favourite accounts saved, even after the page is closed or reloaded. I have tried doing it this way with localStorage, but it does not work for me. Can you help me?
function handleLike() { setLike(!like) }
onClick function
Yes, I see it
when you call the handleLike and you log the value of like what is it?
When I call handleLike it changes and becomes true
looks like it works. what exactly is your issue?
If I reload the 'LIKE_ACCOUNT' page it returns false
try adding this to your useEffect:

if (localStorageData !== null) { setLike(JSON.parse(localStorageData)); }

as in

useEffect(() => { const localStorageData = localStorage.getItem('LIKE_ACCOUNT'); if (localStorageData !== null) { setLike(JSON.parse(localStorageData)); } }, []);

check if a value exists in localstorage first
Value exists in localstorage, but if I reload the page, even with the code you wrote, it returns false
@Michele Value exists in localstorage, but if I reload the page, even with the code you wrote, it returns false
hmm. are you getting any errors whatsoever?

try clearing the localstorage and try it again
I do not receive any errors. I tried cleaning and redoing it, but again after the page has reloaded, it gives me false
i think it has something to do with the use client directive in Next 13.
@Michele I do not receive any errors. I tried cleaning and redoing it, but again after the page has reloaded, it gives me false
try updating your useEffect to use async/await like so:

useEffect(() => { async function likedAccount() { const localStorageData = await JSON.parse( localStorage.getItem("LIKE_ACCOUNT") as string ); if (localStorageData) setLike(localStorageData); } likedAccount(); }, []);
you can ignore the as string if you're not using Typescript
OK now it works, it stays selected for me. But there's another problem, I have several accounts and consequently I can like several accounts. Now if I select more than one, it only keeps one saved for me
then you need to update your state's data structure to an array
i'm guessing each account has a unique identifier, yeah?
Yeah exactly. Any account has a unique id