Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle vuex store to fetch data from rest api?

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!

like image 375
Fausto Sanchez Avatar asked May 17 '18 02:05

Fausto Sanchez


1 Answers

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')
  }
}
like image 88
Frondor Avatar answered Sep 22 '22 11:09

Frondor