Mikhail Krivosheev
Mikhail Krivosheev

Reputation: 569

Axios request from VUEX storage

Is sending data to the server from a VUEX storage:
(something like this)

setTrackingData (state, value) {
  state.to_the_final_destination = value.to_the_final_destination;
  const res = axios.get("https://seo-gmbh.eu/invest/input.php");
}

Does it a normal thing in the vue.js (nuxt.js) development community? )
Are such approaches acceptable?

Upvotes: 1

Views: 692

Answers (1)

BirukAbreham
BirukAbreham

Reputation: 86

In Vuejs if you are using Vuex as a general store you can write the requests in the actions section of the Vuex module. For more information on structuring your Vuex store checkout the link here

Set the state and getters in the Vuex module

const state = {
  ...
};

const getters = {
  ...
};

In the actions object add the code for requesting the server

const actions = {
  async setTrackData({ commit }, value) {
    try {
       const res = await axios.get("https://seo-gmbh.eu/invest/input.php");
       commit("SET_TO_THE_FINAL_DESTINATION", value);
       ...
    } catch (error) {
       ...
    }
  },
};

If you are changing the state of the Vuex by the actions then commit the changes by the mutation function from the mutations object.

const mutations = {
  /* set the data to the state value from the state object */
  SET_TO_FINAL_DESTINATION(state, data) {
    ...
  },
};

Finally, to use the Vuex store actions and getter you have to import the getters in the computed section and the actions in the start of the methods object. Here is an example,

export default Vue.component('ABC', {
  ...
    computed: {

    ...mapGetters([
      /* import the getters here */
      'getSomeState',
    ]),
  },
  ...
  methods: {
  ...mapActions([
     /* import the actions here */
     'setTrackData',
  ]),
  ...
  }
}

To further structure your API calls in a Vuejs project checkout this link here

Upvotes: 3

Related Questions