I'm building a todo List in React, and using Local Storage to save my todos so every time I refresh, they stay displayed.
The issue I'm facing is that whenever I refresh my page, the local storage gets cleared, which is weird because when I've used local storage using Vanilla js and usually got it to do what I wanted. Anyway, here is a snippet of my code:
const [todos, setTodos] = useState([]);
useEffect(()=>{
getLocalTodos();
}, [])
useEffect(() =>{
filterHandler();
saveLocalTodos();
}, [todos, status]);
const filterHandler = () =>{
switch(status){
case 'completed':
setFilteredTodos(todos.filter(todo => todo.completed))
break;
case 'todo':
console.log("herex")
setFilteredTodos(todos.filter(todo => !todo.completed))
break;
default:
setFilteredTodos(todos);
break;
}
}
const saveLocalTodos = () => {
localStorage.setItem("todos", JSON.stringify(todos))
}
const getLocalTodos = () =>{
if(localStorage.getItem('todos') === null){
localStorage.setItem("todos", JSON.stringify([]));
}else{
let todoLocal = JSON.parse(localStorage.getItem("todos"))
setTodos(todoLocal)
}
}