0

I have been working in vue/vuex for about a year. In my apps, find myself eventually adding a couple of mutators in my store(s) like so

mutations: {
...
setAny(state, obj){
  Object.keys(obj).forEach(k => state[k] = obj[k]);
},
toggleAny(state, key){//booleans
  state[key] = !state[key];
}
...

Then I can quickly get objects or multiple objects in the state with patterns like this:

actions:{
  myAsyncThing:({commit}) => {
    asyncThing.then(results => {
      const foo = specialSauceA(results);
      const bar = specialSauceB(foo);
      const baz = specialSauceC(bar);
      commit('setAny', {foo, bar, baz});//slick one liner!
    });
  },
  ...
},
state:{
  foo:{},
  bar:{},
  baz:{}
},

I prefer this over writing a mutator for every shared state key I might update. Of course, I also write plenty of custom mutators, but I have been leaning towards this approach when I need to add props to the state that need to be reliably reactive and set from an action or component.

The reason I ask is mostly I wonder why I have never seen any vuex code examples that do this and I wonder why not? When I first did this, I felt naughty, but over time, this pattern has been a huge time saver with no real side effects.

So is there a flaw with this approach given the discussion surrounding breaking state mutations out of actions and into mutations?

Ron Gilchrist
  • 859
  • 1
  • 8
  • 21
  • 1
    I'd say this is mostly down to personal opinion but you're really creating code that is _not_ self-documenting. There's also a little [_declarative_ vs _imperative_](https://stackoverflow.com/q/1784664/283366) coding in here as well. With your state management (store), you're creating an API. How intuitive that API is, is up to you since you're the one using it – Phil Dec 27 '18 at 22:27
  • 1
    I am of the school of thought to not write an abstraction function for documentation purposes. But I really appreciate the perspective. I enjoy the critique regardless. I admit once in a while a dev will tell me my code does too much in too few lines, so that is my cue to ease off the declarative/functional throttle a bit - heh. – Ron Gilchrist Dec 27 '18 at 22:45
  • 1
    Evan You, creator of Vue, gives his opinion in depth about this subject here https://github.com/vuejs/vuex/issues/234 – Louis Ameline Jul 31 '19 at 14:18

1 Answers1

2

I thing your approach is ok. Because so much double code with mutations some times. If you will see Vuex 4.x in https://github.com/vuejs/roadmap it has

Getting rid of the need for separating actions and mutations

that mean what you are a step ahead

Maxim
  • 2,233
  • 6
  • 16
  • 1
    Thanks for the answer and the roadmap. Looking forward to 4.x. I really want the ability to add global mapped props (like a utility getter I can call anywhere without all the import declarations). But that's for another thread! – Ron Gilchrist Dec 27 '18 at 22:34