GabVlado
GabVlado

Reputation: 75

LocalStorage in NextJS , useEffect problem

I have a problem to get and set data in localStorage, i use NextJs then i can´t use localStorage initially.

I try to resolve with a useEffect but I have a infinite loop, i know that it's for the dependency. I don´t know the best way to resolve the problem, with a useCallback or useMemo or useRef.

I paste a part of the code with the problem.

      const [ meetings, setMeetings] = useState([]) // meetings= [{meeting1},{meeting2}]
      
      useEffect(() => {

       if(localStorage.getItem('meetings') === undefined || 
         localStorage.getItem('meetings') === '' ||
         localStorage.getItem('meetings') === null
         ){
          localStorage.setItem('meetings', JSON.stringify([]))         
         }


       if( JSON.parse(localStorage.getItem('meetings')).length === 0){
            
             const meetingsInLocalStorage  = JSON.parse(localStorage.getItem('meetings'))
             setMeetings([...meetings, meetingsInLocalStorage])

       }
       },[meetings])

Upvotes: 0

Views: 954

Answers (1)

a.mola
a.mola

Reputation: 4011

You can shorten this conditional to

localStorage.getItem('meetings') === undefined ||  localStorage.getItem('meetings') === '' || localStorage.getItem('meetings') === null

This

!localStorage.getItem('meetings')

This snippet of code doesn't make sense because, if the data from the localStorage is empty

if (JSON.parse(localStorage.getItem('meetings')).length === 0) {

This will be empty as well

const meetingsInLocalStorage = JSON.parse(localStorage.getItem("meetings"));

And when you spread the meetings array, you don't spread the meetingsInLocalStorage, you keep pushing the empty array into the meetings state.

setMeetings([...meetings, meetingsInLocalStorage]);

Your data will look like [ [], [], ...], and the meetings variable changes, so the useEffect runs again leading to the infinite loop.

Finally


I assume you want to update the meetings state if there were some in the localStorage

So your check should be

if (JSON.parse(localStorage.getItem("meetings")).length > 0) {
  const meetingsInLocalStorage = JSON.parse(localStorage.getItem("meetings"));
  setMeetings([...meetings, ...meetingsInLocalStorage]);
}

Upvotes: 1

Related Questions