My linter is bullying me.
I made a function to set tasks completed
to !completed
with ids as parameters
The data looks like this:
const lists = [
{
id: 'todo-3',
name: 'Example 3',
tasks: [{ name: 'task', completed: true, id: "Un" },{ name: 'task2', completed: true, id: "Deux" },{ name: 'task3', completed: true, id: "Trois" }]
}
{
id: 'todo-4',
name: 'Example 5',
tasks: [{ name: 'task', completed: true, id: "Un" },{ name: 'task2', completed: true, id: "Deux" },{ name: 'task3', completed: true, id: "Trois" }]
}
]
At first, I made a function like this and it works but the linter didn't like it.
const toggleTask = (listId: string, taskId: string) => {
const newListsToggled = lists.map((listItem) => {
if (listItem.id === listId) {
listItem.tasks.map((task) => {
if (task.id === taskId) {
task.completed = !task.completed;
}
return task;
});
}
return listItem;
});
};
"task.completed = !task.completed" this part gave me the No-param-reassign error so I tried another function:
const toggleTask = (listId: string, taskId: string) => {
const newListsToggled = lists.map((listItem) => {
if (listItem.id === listId) {
return listItem.tasks.map((task) => {
if (task.id === taskId) {
return {...task, completed: !task.completed}
}
return task;
}
);
}
return listItem;
});
console.log('testtoggle',newListsToggled)
};
toggleTask('todo-3','Deux')
This one doesn't return the whole array, the lists.name
and lists.id
parts are gone.
Without bypassing the linter is there any way to solve this function?
This one doesn't return the whole array, the lists.name and lists.id part are gone
To solve this problem, instead of returning return listItem.tasks.map(...)
, you can use the same object spread trick you have used with task:
if (listItem.id === listId) {
return {
...listItem,
tasks: listItem.tasks.map(...)
}
}