Home > Net >  Problem with Vuex data mutation inside action due to reactivity
Problem with Vuex data mutation inside action due to reactivity

Time:12-18

I have an action in my Vuex store that should make a call to the API with new data to be updated.

I want to create an object that is a copy of an existing value in my store and mutate it freely without being impacted by reactivity.

Right now, when I do the Array.push() call, I run into this error Do not mutate vuex store state outside mutation handlers, how could I do it differently ?

(I have a getter on rootState.phone.policy.currentPolicy.attributes.insured.phones which my explain this error).

  async [PolicyActionTypes.UPDATE_POLICY](
    { rootState },
    payload: UpdatePolicyPayload
  ) {
    const newPolicy: Policy = {
      ...rootState.phone.policy.currentPolicy,
    };

    const newPhone: Phone = {
      imei: '123',
      brand: 'Samsung',
    };

    newPolicy.attributes.insured.phones.push(newPhone);

    // Fake async API call
    api.updatePolicy(newPolicy)
  },

CodePudding user response:

When you spread, you're making a shallow copy, hence you still reference the old object.
When you do mutate the object, you think that it's a deep copy, while it's still the old one.

More info on my answer here.

TLDR: cloneDeep is the way to go here, indeed.

  • Related