Hi everyone before too late and hours, i can't work .
I need update each checkBox, when this is true or false (tasks array are checkBox in front End)
Data seeds
const datas = [
{
id: 10,
name: job01,
tasks: [
{ name: "morning", value: false },
{ name: "afternoon", value: true },
{ name: "sunset", value: false },
{ name: "night", value: true },
],
completed: false
}];
the next code to update data, when press one checkbox is:
const [todos, setTodos] = useState(datas)
const toggleTask = taskId => {
const updateTodos = todos.forEach(to => {
to.tasks.forEach(task => {
if (taskId === to.name)
console.log('update datas: ', { ...task, value: !task.value})
}
})
})console.log('Result: ', updateTodos ) };//only show undefined
Thnz for readme.
forEach does not return anything, you might want to first map the array, and then filter the elements:
// get a list of the tasks that you need to update
const needUpdateTodos = todos.flatMap(
to => to.tasks.filter(task => taskId === to.name)
);
// for each task that you need to update, change the value to the opposite
const updatedTodos = needUpdateTodos.map(el => {
task.value = !task.value;
console.log('update datas: ', task)
return task
})
// show resulting tasks updated
console.log('Result: ', updatedTodos )