6

I'm using Vuex to handle my application state.

I need to make an Ajax Get request to a rest api and then show some objects list.

I'm dispatching an action that loads this data from the server but then I don't know how to handle it on the component.

Now I have this:

//component.js
created(){
      this.$store.dispatch("fetch").then(() => {
        this.objs = this.$store.state.objs;
      })
    }

But I don't think that the assignment of the incoming data to the local property is the correct way to handle store data.

Is there a way to handle this better? Maybe using mapState?

Thanks!

0

1 Answer 1

10

There are many ways you can do it, you must experiment and find the one that fits your approach by yourself. This is what I suggest

{ // the store
  state: {
    something: ''
  },
  mutations: {
    setSomething (state, something) {
      // example of modifying before storing
      state.something = String(something)
    }
  },
    actions: {
      fetchSomething (store) {
        return fetch('/api/something')
          .then(data => {
            store.commit('setSomething', data.something)
            return store.state.something
          })
      })
    }
  }
}

{ // your component
  created () {
  this.$store
    .dispatch('fetchSomething')
    .then(something => {
      this.something = something
     })
    .catch(error => {
       // you got an error!
     })
  }
}

For better explanations: https://vuex.vuejs.org/en/actions.html

Now, if you're handling the error in the action itself, you can simply call the action and use a computed property referencing the value in the store

{
  computed: {
    something () { // gets updated automatically
      return this.$store.state.something
    }
  },
  created () {
    this.$store.dispatch('loadSomething')
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You don't need to wrap fetch in a new Promise as it already returns a promise. The action should also return the promise.
If you see the example, the action is committing a mutation that modifies the response before storing it. You have to resolve that fetch before returning the promise. But yeah, it's just one of the many cases I mentioned. There are plenty of different ways to do it.
return fetch().then(data => /* commit and return whatever */), it's redundant to wrap the promise inside a promise.

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.