[Vuejs]-Vue: Is it possible to set another state inside a Vuex action?

3đź‘Ť

âś…

The following is a fairly common pattern, borrowed from this post:

const actions = {
  fetchApiData (store) {  
    // sets `state.loading` to true. Show a spinner or something.
    store.commit('API_DATA_PENDING') 

    return axios.get('someExternalService')
      .then(response => {       
        // sets `state.loading` to false 
        // also sets `state.apiData to response`
        store.commit('API_DATA_SUCCESS', response.data) 
      })
      .catch(error => { 
        // set `state.loading` to false and do something with error   

        store.commit('API_DATA_FAILURE', error)
      })
    }
}

Add a loading flag to your state. It may make sense to group loading and toggleProgram mutations together. The “pending” mutation could toggle the loading to true, while the “success” and “failure” commits would set loading to false and mutate the program state as desired.

Doing this for every ajax post could get tiresome, so a next step could be to add an abstraction.

👤rossta

Leave a comment