Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to call an action from within another action in Vuex?

Tags:

vue.js

vuex

I'm considering the following two alternatives in my Vue app. Trying to decide whether to call an action from within another action, or if that's too messy.

Alternative one:

store.js

const actions = {
    funcOne (context) {
        //Do something
        context.dispatch(funcTwo)
    }
    funcTwo () {
        //Do something else
    }
}

component.vue

methods: {
    doSomething () {
        this.$store.dispatch(funcOne)
    }
}

Or alternative two:

store.js

const actions = {
    funcOne () {
        //Do something
    }
    funcTwo () {
        //Do something else
    }
}

component.vue

methods: {
    doSomething () {
        this.$store.dispatch(funcOne)
        this.$store.dispatch(funcTwo)
    }
}

Is there a best practice here or does it not matter which of these I choose?

like image 236
Matt Avatar asked Dec 28 '25 04:12

Matt


1 Answers

It is not bad practice! They are designed to be composed easily, and the documentation even has examples for it.

If actions are tightly coupled, i.e. one should only be called after the other in every case, then it is better practice to dispatch the action and then have the first action call the second.

If they are decoupled, i.e. calling them in any order is fine and they can be used separately, you can communicate this better in coding style by calling both actions from the method.

Keep in mind that actions are intended for asynchronous actions, so make good use of async/await and they'll much very easy to manage.

like image 107
Arc Avatar answered Dec 30 '25 22:12

Arc