TommyD
TommyD

Reputation: 1043

Vuex returning some data back the the component

I have an axios call in my vuex actions

  return axios({
      method: 'get',
      url: `/myurl`,

    }).then(function (response) {
      context.commit('value', response.data.data);
    }),

However this is called in my component

this.$store.dispatch("fetchmystuff")

How do I return a value to the component?

In the past I have attached the then() to the dispatch

 this.$store.dispatch("fetchmystuff")
    .then(function (response) {
     //do some component stuff
 }),

but I would like to run the commit first in vuex, then return something to the component.

Upvotes: 1

Views: 472

Answers (1)

Denis Tsoi
Denis Tsoi

Reputation: 10404

You've dispatched the action fetchmystuff. From within your component, you will want to either.

1. query the store for the state of value

computed: {   
  value() {    
    return this.$store.state.value
  } 
}

2. call a getter which gets the state of value from a computed property

in component

computed: {   
  value() {    
    return this.$store.getters.value
  } 
}

in store getters.js

getters: {
  // ...
  value: (state, getters) => {
    return getters.value
  }
}

The dispatcher/action shouldn't need to access to the component
(as state is only set in store via mutations/commits, and have state passed to other components via getters).

This allows a decoupling of concerns between the store and the component parts of your application.

Upvotes: 1

Related Questions