skip to Main Content

I need to use localStorage in nextjs but after refresh i lose all the data (empty array [] in the console).
this is what i tried:

 const [todos, setTodos] = useState([]);

  useEffect(() => {
    const storedTodos = JSON.parse(localStorage.getItem('todos')) || [];
    setTodos(storedTodos);
  }, []);

  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
  }, [todos]);

This works in React:

const [todos, setTodos] = useState(
    () => JSON.parse(localStorage.getItem('todos')) || []
  );

but in nextjs i see localstorage is not defined.

Thank you!

2

Answers


  1. Chosen as BEST ANSWER

    the useEffect was resetting the localStorage every refresh, so i added todos.length === 0 to check:

    const [todos, setTodos] = useState([]);
    
      if (typeof window !== 'undefined') {
        if ((localStorage.getItem('todos')) === null) {
          localStorage.setItem('todos', JSON.stringify([])); // initialize here to prevent the null pointer in useeffect (todos.length)
        }
      }
    
      useEffect(() => {
        const storedTodos = JSON.parse(localStorage.getItem('todos'));
        setTodos(storedTodos);
      }, []);
    
      useEffect(() => {
        
        if (todos.length === 0) {
          console.log("Array is empty!")
        } else {
          localStorage.setItem('todos', JSON.stringify(todos));
        }
      }, [todos]);
    

  2. Try just localStorage.setItem('todos', "test"); without useEffect and check your whether your browser has saved it in local storage.

    Please also make sure you’re setting it in a class/function component.

    localstorage

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search