javascriptvue.jsecmascript-6vuexecmascript-2018

What does { ...obj1, obj2 } do exactly


Let's say we have two objects:

const state = {
  fishes: { /* some obj data */ },
  animals: { /* some obj data  */ }

const animals = { /* some NEW data */ }

In Vuex there is a method replaceState(), which according to the documentation takes one argument and replaces the state with that object.

What will be the result of the following:

replaceState({ ...state, animals })

More specifically, what does { ...state, animals } do exactly?

To bring some context, I took this example from the answer of this question. In that question, the user wanted to replace the animals property of the state with the new object animals.

I'm not sure if this is relevant to Vuex / Vue.js, or is it a pure JS question, but I'll tag it with vue.js anyway.


Solution

  • This is actually from ECMAScript 2018's spread syntax and ECMAScript 2015's object destructuring.

    { ...state, animals } creates a shallow copy of the state object, with a new property called animals (with the value of animals object within it).

    Since you are a Vuex user, this conforms to the rule of immutable update patterns, which is to prevent the 'original' state object from being altered or mutated. You should read up on the ways of handling common operations such as add/update/delete, using the immutable pattern.