T
T
tryToFrontEnd2021-12-10 15:12:22
Vue.js
tryToFrontEnd, 2021-12-10 15:12:22

How to correctly call methods for API requests?

There is 1 option

methods: {
  ...mapActions('module name', ['getData'])
},
mounted() {
  this.getData();
},

actions: {
  async getData({ commit }) {
    try {
      const response = await axios.get(url);
      commit('mutation name', response.data);
    } catch (e) {
      console.error(e);
    }
  },
},


and 2 second option, if I get the result of the request in the component itself

methods: {
  ...mapActions('module name', ['getData'])
},
mounted() {
  this.getData().then((res) => {
    if(res.status !== 200) {
      console.log('Error')
    }
  });
},

actions: {
  async getData({ commit }) {
    try {
      const response = await axios.get(url);
      commit('mutation name', response.data);
      return response;
    } catch (e) {
      console.error(e);
      return null;
    }
  },
},


Is it correct to write like that?
And the second question, I often see when instead of try / catch they use
axios.get(url)
  .then()
  .catch(e)
  .finally()

async getData({ commit }) {
    return await axios.get(url).then((res) => {
      commit('mutation name', res.data)
    }).catch(e => console.error(e));
    }
  },


Which option is preferable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WapSter, 2021-12-10
@wapster92

1. Don't want to read the doc? How do you refer from mounted to a function from the store?
https://vuex.vuejs.org/guide/actions.html#dispatch...
2. No difference

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question