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
the
useEffect
was resetting thelocalStorage
every refresh, so i addedtodos.length === 0
to check: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