Home > database >  VueJS Vuex Action explanation
VueJS Vuex Action explanation

Time:03-28

I'm a beginner in vueJS and I'd like to know something about actions. As far as I know, I've seen that they would handle asynchronous code while mutations hold synchronous one. I'd like to understand something . Let's suppose I call an API when a component / view gets mounted :

mounted(){
          fetch("http://localhost:100/api/v1/tags")
          .then(response =>
            response.json())
          .then(
           data => { 
            this.dbTags = [...data.map(item => item.nom)]
            this.$store.commit('changeTagsApiValueToTrue');
            }
          ) 

I used commit here and it works but I want to know whether it is correct to use it when the code outside of the action is asynchronous. What I mean is, does the code inside the action part of the vuex file should be asynchronous or every single asynchronous functionality that is using vuex (such as fetching an api from a component / view ) should have its data handled by actions.

CodePudding user response:

There is nothing wrong with calling a synchronous method from an asynchronous chain.

You only need to use actions (aka dispatch) when your call into the store uses asynchronous code.

In other words, if your call to commit called fetch, you should use dispatch instead.

store.dispatch('doFetch', 'http://localhost:100/api/v1/tags')

Then your 'doFetch' action would call fetch, and eventually call commit

If your address was always the same, it would simply be:

store.dispatch('doFetch')
  • Related