9

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?

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

4 Comments

can u explain why in the author doesn't have to do so? I mean do updated[0].id
the tutorial is here egghead.io/lessons/…
because in his case, arr2 will be an object, like this: const arr2 = {id:2,name:'this should be a new string'} you can try this arr2, ur code will also work :)
ah arr2 should be an object, it shouldn't be an array, I think that's my mistake, that doesn't make sense if arr2 is an array.
1

It's simpler and cleaner using Array.map:

const updateTodo = (list, updated) =>
    list.map((item) => {
        if (item.id !== updated.id) {
            return item;
        }

        return updated;
    });

Comments

0

For some reason the updated argument is an array, and therefore updated.id wont work. In that case, if you want to update the list item with that id the cleanest way to update list without mutating it would be to use Array.prototype.with() :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.