Skip to content
Advertisement

update array of object without mutation

I’m following a react tutorial but I’m lost. I don’t understand starting line 9.

enter image description here

so I tried to make a little miarature

const updateTodo = (list, updated) => {
   const index = list.findIndex(item => item.id === updated.id)
   return [
   ...list.slice(0,index),
   updated,
   ...list.slice(index+1)
   ]
}

https://jsbin.com/sifihocija/2/edit?js,console but failed to produce the result that the author did, what’s wrong?

Advertisement

Answer

Issue is in this line:

const index = list.findIndex(item => item.id === updated.id)

updated is an array, to access the id, you need to specify the index also, for other array you are using loop, so item will be the each object of the array, and item.id will give you the id of each object, try this:

const index = list.findIndex(item => item.id === updated[0].id)

const arr = [
  {id:1,name:'hello'},
  {id:2,name:'hai'}
]

const arr2 = [
  {id:2,name:'this should be a new string'}
]

const updateTodo = (list, updated) => {
   const index = list.findIndex(item => item.id === updated[0].id);
   return [
   ...list.slice(0,index),
   ...updated,
   ...list.slice(index+1)
   ]
}

console.log(JSON.stringify(updateTodo(arr,arr2)))

Check the working code: https://jsbin.com/pazakujava/edit?js,console

Let me know if you need any help in this.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement