I have a reducer for state management at the context API. I was saving my Todos and it's happening successfully but when ı refresh the page all todos is deleting and just stay empty array.
// The relevant part in the reducer.
case "TODO_ADD_USER":
return {
...state,
users: action.payload,
};
// Localstorage functions.
useEffect(() => {
saveLocalTodos();
}, [state]);
useEffect(() => {
const localTodos = getLocalTodos();
dispatch({ type: "TODO_ADD_USER", payload: localTodos });
}, []);
const saveLocalTodos = () => {
if (localStorage.getItem("users") === null) {
localStorage.setItem("users", JSON.stringify([]));
} else {
localStorage.setItem("users", JSON.stringify(state.users));
}
};
const getLocalTodos = () => {
let locals;
if (localStorage.getItem("users") === null) {
locals = [];
} else {
locals = JSON.parse(localStorage.getItem("users"));
}
return locals;
};
Place of keeping the state.
const users = {
users: [],
};