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?
The warning is triggered by the fact that in your .map(task => ... ) you modify task (before then returning it). The way you use map has a side effect on the input collection. It could be intentional, or it could be irrelevant, but it still is happening.
The purpose of .map() is usually to generate a new result object/value for each input object/value. You should (almost) never change the input values, which is what you are doing, you should only generate output values.
If you actually want to modify the input values, it is better to use .forEach instead:
if (listItem.id === listId) {
listItem.tasks.forEach((task) => {
if (task.id === taskId)
task.completed = !task.completed;
}
}
return listItem;
This can be combined with .filter instead of the if:
if (listItem.id === listId) {
listItem.tasks
.filter(task => task.id === taskId)
.forEach(task => task.completed = !task.completed);
}
return listItem;
Or if you know there is never more than 1 matching task, then you can use .find:
if (listItem.id === listId) {
var task = listItem.tasks.find(task.id === taskId);
if (task) task.completed = !task.completed;
}
return listItem;
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(...)
}
}