I have an object with a simplified structure like so:
state = {
todo: {
1: {text: 'Buy apples'},
2: {text: 'Buy milk'}
}
}
If I wanted to remove a todo item immutability, according to other answers on Stack Overflow I could destructure the todo's list:
const idToDelete = 2
let {
[idToDelete]: deleted,
...newTodo
} = state.todo
If I do console.log(newTodo)
, then it has the same value of state.todo
, meaning that it hasn't removed to todo item with id of 2. If I console.log(deleted)
then it returns the contents of the todo I want to delete: {text: 'Buy milk'}
.
I'm aware that it would be somewhat easier to manage this using a library such as Immutable.js, however I would like to know why destructuring the object does not remove the todo item. Thanks.
You will need stage-0 to achieve what do you want. If you check my code you will see that if you use a string to destruct the params it will works as you expect but if you use a number variable, the result will be the full object. I guess this should be a bug in the implementation.
const state = {
todo: {
1: {text: 'Buy apples'},
2: {text: 'Buy milk'}
}
}
const id = 1
const { [id]: deleted, ...newTodo } = state.todo
console.log(deleted)
console.log(newTodo)
/********* GOOD EXAMPLE *********/
const { [id.toString()]: del, ...goodNewTodo } = state.todo
console.log(del)
console.log(goodNewTodo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With