Coder
Coder

Reputation: 610

What's the difference between list: {[id]:array1} and list: {...state.list, [id]:array1} in ReactJs?

This is my state:

state = {
    list: {}
};

In some function I change my state to:

let id = 'ab12'
let array1 = [{a: 'hello', b: 'hi'}, {a: 'how', b: 'are'}]
this.setState({
    list: {
        ...state.list,
      [id]: array1
    }
});

I didn't understand why I use(I am referring someone else's code) :

list: {
  ...state.list,
  [id]: array1
}

But Not :

list: {
  [id]: array1
}

For both I got the same result when I tried in MDN web tool and this is what I tried:

let state = {
    list: {}
}
let id = 'ab12'
let array1 = [{a: 'hello', b: 'hi'}, {a: 'how', b: 'are'}]
state = {
  list: {
    ...state.list, 
    [id]: array1
  }
}
console.log(state.list)

and this:

let state = {
    list: {}
}
let id = 'ab12'
let array1 = [{a: 'hello', b: 'hi'}, {a: 'how', b: 'are'}]
state = {
  list: {
    [id]: array1
  }
}
console.log(state.list)

What's the difference?

Upvotes: 0

Views: 49

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104369

In short: One way will concatenate the old key values and new key value and other one will simply replace the old object with new object, which will have only one key.


In your case, there is not difference between these two ways, Because list contains only one key:

list: {
  ...state.list,
  [id]: array1
}


list: {
  [id]: array1
}

Lets assume list is something like this:

list = {
   name: 'abc',
   address: 'abc',
}

Now you want to add an array here, by below approach it will add a new key to existing object and all other keys will remain unchanged:

let id = 'ab12';
let array1 = [{a: 'hello', b: 'hi'}, {a: 'how', b: 'are'}];

list = {
   ...list,
   [id]: array1
}

// list = {name: 'abc', address: 'abc', ab12: [...] }

But if you write:

list = {
   [id]: array1
}

Output will be: list = { ab12: [....] } only, name and address will be removed.

Upvotes: 1

mcssym
mcssym

Reputation: 944

list: {
  ...state.list,
  [id]: array1
}

helps you keep the previous values of the list just add the news one. It is like concatenation of the previous values with the new one. It is like using Object.assign: if a key already exist, his value will be update else a key/value is added to the object. but this

list: {
  [id]: array1
}

just replace the previous value by a new one.

Upvotes: 1

Related Questions