i have a todolist, but i want de data to stand in the page when i reload. Im trying to work with local storage but im having problems with it. Im using setItem and getItem, but it isn`t working.
const [todos, setTodos] = useState([]);
useEffect(() => {
const data = window.localStorage.getItem("todoStorage");
setTodos(JSON.parse(data));
}, []);
useEffect(() => {
window.localStorage.setItem("todoStorage", JSON.stringify(todos));
}, [todos]);
2
Answers
well guys, i found an indian youtuber that helped me with that, im gonna post the code that fix that problem for me:
The issue you’re experiencing could be related to the initial state of the todos array. When the component is first rendered, the useEffect that reads from localStorage runs, and if there is no data in localStorage, it sets todos to null (since JSON.parse(null) results in null).
To fix this issue, you can add a check to see if the data retrieved from localStorage is not null before setting the state. If it’s null, you can initialize todos to an empty array. Here’s how you can modify your code:
In this modified code, if the data retrieved from localStorage is not null, it will set the todos state with the parsed data. If the data is null, it will keep todos as an empty array. This way, even if there is no data in localStorage, todos will always be initialized as an empty array, preventing unexpected behavior when you reload the page.