Search code examples
javascriptvue.jsvuejs2vuex

Is it good practice to mutate Vuex with Vue.set with an object that is also an observable


Expected to achieve: Most correct way to modify specific record stored in the Vuex state with one big (batch) write

Context: Vuex state contains list of records with default values for each record.

Logic Component initialises and uses getter to get one of the records. It's needed to add new properties to the record and overwrite existing values.

Question Is it acceptable to modify the object returned by the Vuex getter and later commit the whole result into the state? And if yes, what would be the best approach considering it will have to overwrite existing record in Vuex.

P.S: I also wonder if it can result in breaking behaviour of other components that are "getting" the same record that will be overwritten, and will appreciate a lot your thoughts on this topic :-)


Solution

  • Don't modify Vuex data except via Vuex mutation

    1) First, clone the getter record. Make sure you deep clone if your record has anything but primitive properties, i.e it has properties that are objects or functions. Here are some cloning options, notice that many don't correctly deep clone.

    2) Once you're done mutating the clone, call a Vuex action and have that action call a mutation. It's good practice to only call mutations from actions.

    3) In that mutation, use Vue.set (or splice) to replace the state record.

    4) Yes, if you mutated the getter directly, it would be mutated anywhere else it was used.