Armen Barsegyan
Armen Barsegyan

Reputation: 57

How to write async code inside vuex action object?

I have Rest api for my vue.js app, and want to know is there any other way to write async code using vuex?

My code looks like this

//store.js

const actions = {
    async GET_CLAN_MEMBERS({commit},id){
        let token = users.getters.getToken;
        return await axios.post(config.api + 'clans/' + id,{token})
    }
};

//Component.vue

created (){       
   this.$store.dispatch('GET_CLAN_MEMBERS',this.$route.params.id).then((res) => 
   {
      this.members = res.data;
   })
},

Now it's working but I don't know is it the best place or practice write it inside store.js file.
Thanks in advance.

Upvotes: 1

Views: 172

Answers (2)

Sombriks
Sombriks

Reputation: 3622

me too, got this question over my head and indeed store can consume rest api's inside their actions.

This is why vuex support modules, to avoid too big store files.

I did a few experimentation here (missiang the modularization but works as a good example), and the official documentation itself says to call the async operations inside actions. So, axios/rest inside actions are the recommended way.

Upvotes: 0

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

standard practice : actions always used as setter , so after api call back response you should call mutation to change state based on response data, and getters used as getter(state data retrieval)

So you should follow below flowchart for standard practice:

enter image description here

For more info read here

Upvotes: 1

Related Questions