vuejs-templates / pwa

PWA template for vue-cli based on the webpack template
MIT License
3.04k stars 506 forks source link

HELP: VueX and no-param-reassign #189

Closed aprilmintacpineda closed 6 years ago

aprilmintacpineda commented 6 years ago

Hi, I'm new to Vue and I am using this template for my first Vue Application. I also am going to use VueX.

In VueX, the only way for us to mutate the state is by changing the state passed to the mutation handler as a parameter (https://vuex.vuejs.org/guide/mutations.html#mutations-follow-vue-s-reactivity-rules), which of course would lead to error because of no-param-reassign.

I just want to know how you guys deal with this. Please give me insights as I really need to mutate the state by doing:

state = {
   ...newState
};

I've tried returning the newState as that's what we do in redux but apparently in VueX that's not the case because returning the newState will not update the store.

Do @mention me for any response please...

LinusBorg commented 6 years ago

I just want to know how you guys deal with this. Please give me insights as I really need to mutate the state by doing:

state = {
   ...newState
};

Well, even if you get eslint to allow this (you can simply disable the rule) - this will do nothing to the state in vuex. You just changed the reference of the local variable called state inside of the mutation - the state object that this variable pointed to before this change is not affected.

You can't completely replace the original root state (of vuex as a whole or a store module) with a new one. Vuex is not built around immutable principles because they are orthogonal to the Reactivity that Vue is built upon, so you have to mutate the state.

However, you can overwrite attributes like this:

Object.assign(state, newState)

If you really need to completely replace a piece of state, then save that original piece of state as a property, not as root properties:


// in your store (module)
const state = {
  someProp = {
    /* this is the object you wnt to replace */
  }
}

const mutations = {
  SOME_MUTATION: (state, newState) => {
    state.someProp = newState
  }
}
aprilmintacpineda commented 6 years ago

Thanks.

rsmithlal commented 4 years ago

This should help: https://github.com/vuejs/vue-cli/issues/3954#issuecomment-490670529