I'm trying to make a todo list app by using React and Material UI. Everything works fine except checkbox state. I'm saving each todo as object in todo list array in local storage as below.
- todoList is the state that I store each todo.
- isCompleted also a state with default boolean value of false
let arr = todoList;
const newTodo = new TodoItem({
id: randomID,
text: text,
date: date,
status: isCompleted
});
setTodoList([newTodo, ...arr]);
localStorage.setItem('todos', JSON.stringify(todoList));
In another component I get saved items from local storage by useEffect and render them as todo list. I'm trying to get stored items every time isCompleted changes.
useEffect(() => {
let savedItem = JSON.parse(localStorage.getItem('todos'))
if (savedItem !== null) {
setTodoList(savedItem);
}
}, [isCompleted])
- This is the checkbox that should change read status.
<FormControlLabel
control={
<Checkbox
onChange={(e) => changeStatus(e.target.checked,index)}
color="primary"
/>
}
/>
- This is the function supposed to change status. Click handler works fine, it changes status with each click. However, the problem is when I refresh the page, checkbox resets itself to empty state even though status of todo completed in local storage.
const changeStatus = (val,num) => {
let item = todoList[num];
if(val === false){
setIsCompleted(true);
item.status = isCompleted;
}else if(val === true){
setIsCompleted(false);
item.status = isCompleted;
}
let storedItems = [...todoList];
itemsToRender = storedItems;
storedItems = storedItems.map(todo => todo.id === item.id ? todo = item : todo)
console.log('STORED',storedItems);
localStorage.setItem('todos', JSON.stringify(storedItems));
}
- note that I'm mapping itemsToRender array to display todos in the component.
How can I prevent checkbox to reset itself(unchecked), I need checkbox to stay checked after reloading the page.
To me, I'm doing something wrong with useEffect or MUI checkbox component.
Thanks in advance for any help or advice.