1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks that was kind of how I did it in other places, it just seemed an 'alternative' way to go! I though I could have done it without checking the $store.state.
Yes you're correct that you can remove the instances of store from the axios fetch method - so this is the trade off you need to make when leveraging Vuex store (reusable methods via actions or leaving the method isolated within a component)
In my case, the component might exist twice (regular and sometimes in modal div). Both components must have different states, that can be modified by a dispatched functions return value. So one state of value won't work, because in this case, both components values would be the same from $store.state. How can I solve this?
Have you asked this question SO @Dong3000
@DenisTsoi I've made it concrete here: stackoverflow.com/questions/64842269/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.