MaratSR
MaratSR

Reputation: 87

Correct way create action in vuex

Is it enough to create simple (without chaining then/catch calls) vuex-actions as a1? Or I need write it each time with Promise creating as a2 (+also add reject branch)?

Thank you in advance...

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production';

export default new Vuex.Store({
    state: { ... }
    ...
    actions: {
        a1: (state, response) => {
            state.commit('setNavMenu',{signIn: true, signUp: true, signOut: false});
        ...        
        },
        a2: (state, response) => {
            return new Promise((resolve) => {
                state.commit('setNavMenu',{signIn: true, signUp: true, signOut: false});
            ...
            resolve();
            });
        },        

...
     

Upvotes: 2

Views: 917

Answers (2)

Daniel
Daniel

Reputation: 35724

You don't, you would only do that if the action has an asynchronous aspect or want to get a response from your action.

If all your updates are of synchronous nature (not relying on an API or any asynchronous feedback), you could even call the mutations directly, skipping the actions altogether.

i.e. (from official doc)

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // map `this.increment()` to `this.$store.commit('increment')`

      // `mapMutations` also supports payloads:
      'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // map `this.add()` to `this.$store.commit('increment')`
    })
  }
}

The reason why you would use an action is when you have are dealing with a asynchronous change, like when you want your mutation to use data that comes from an API.

Upvotes: 0

Eddo
Eddo

Reputation: 197

It is possible to create a synchronous action (without a promise or other asynchronous code) just like your first one a1

However, you could then directly call the mutation function instead, in a1 case, it would be setNavMenu. The main difference between actions and mutations is that actions can be asynchronous when mutations cannot, basically if you do not need your action to perform async. code, you do not need an action and can just go with the mutation.

For further details you can check the official doc on actions https://vuex.vuejs.org/en/actions.html

Upvotes: 1

Related Questions