I have created a todo list for my site where the user is able to add and delete todo items and I am trying to make it so they can check or uncheck the items as they need to.
Right now the ability to add/delete is working fine and the checkboxes update the database when they are clicked as they are suppose to but the problem is that the checkboxes don't update properly on the website.
The state is an array of todo item information from the database. So initially the state is set as the current information from the database:
const [items, setItems] = useState(todo_items)
where todo_items is from the DB and is structured like this:
```
0:
complete: 0 or a 1
todo_id: Integer
todo_item: String
1:
complete: 0 or a 1
todo_id: Integer
todo_item: String
.
.
.
```
Now once this is set as the state I map the todo items to a form:
<form>
{items.map((e) => (
<div id={e.todo_id}>
<div>
<input
type="checkbox"
checked={e.complete === 1}
onChange={(f) => checkHandler(f.target.checked, e.todo_id)}
/>
<p>{e.todo_item}</p>
</div>
</div>
))}
</form>
and then when a checkbox is checked I change the state and update the database to reflect the new representation of all of the checkboxes
async function checkHandler(checked, todo_id){
var updated_todo = items
for (var i = 0 ; i < items.length ; i ){
if (items[i].todo_id === todo_id && checked === true) {
updated_todo[i].complete = 1;
} else if (items[i].todo_id === todo_id && checked === false){
updated_todo[i].complete = 0;
}
}
setItems(updated_todo)
// update database below...
}
I thought this would automatically update the checkboxes on the website every time this state is updated but it doesn't re-map the todo items in the form when the items state is changed.
CodePudding user response:
var updated_todo = items
is a reference to the object so when you change it you also change the state, thats why the app wont rerender when you set the state
try changing that too
var updated_todo = [...items]