1

I'm using the following code to insert a new object into the array 'items'. But the problem is when I insert a new object, it replaces the content of the object that is added just before. In such way, the always contains the same objects, even though added objects are different.

I heard it's due to using 'push' which also passes the reference. How can I fix this is VueJS

Store.js

var store = new Vuex.Store({
  state: {
    value: 1,
    quote: {
      items: [],
      something: ''
    }
  },
  mutations: {
    ADD (state, item) {
      state.quote.items.push(item)
    }
  }
})

2 Answers 2

2

instead use spread operator,

mutations: {
  ADD (state, item) {
    state.quote.items = [...state.quote.items, Object.assign({}, item)]
  }
}

Is spread operator is not needed, you can just do:

mutations: {
  ADD (state, item) {
    state.quote.items.push(Object.assign({}, item))
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@GijoVarghese Possible to create a fiddle of this issue.
@GijoVarghese All add the code where you are commiting this mutation, may be you are pushing the same item again just by changing it's queue. I will update my answer to handle that case.
Tried both, not working. The answer I posted is working. The objects are not same. I thoroughly checked
1

Finally got the answer myself. The solution is 'stringify the object and parse it back, both using JSON'

  mutations: {
    ADD (state, item) {
      item = JSON.stringify(item)
      item = JSON.parse(item)
      state.quote.items.push(item)
    }
  }

1 Comment

Use Object.assign as I have added in my answer.

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.