So I have an array of todos. When I remove a todo I am trying to change the id's of the rest of the items so for example todo[1] also has an id of 1. This is not the case if I have 3 items and remove the first one as the second item will have an id of 2 even though it should be 1.
This is what I currently have-
case REMOVE_TODO: {
const newList = state.todos.filter(item => item.id !== action.id);
for (let i = 0, newId = 0; i > newList.length; i++, newId++) {
newList[i].id = newId;
console.log(newList[i].id); //nothing gets logged
}
return {
...state,
todos: newList
};
}
Instead of correctly changing the item ids nothing happens and even when I console log the id of what I just changed, nothing happens and nothing changes.
Looks like a problem with your iterator in the for loop. i > newList.length
should be i < newList.length
. Also you could use map to loop over the newList and get a newer set of array.
you can do without the loop
. This will be good practice when you have a bunch of data.
const index = state.todos.findIndex(item => item.id == action.id);
const newList = state.todos.splice(index,1);
return {
...state,
todos: newList
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.