R
R
RokeAlvo2019-11-29 09:23:15
Vue.js
RokeAlvo, 2019-11-29 09:23:15

How to use async/await in actions vuex?

I looked at a bunch of answers to this question, but for some reason it doesn’t work in the end:
in sore.js

actions: {
         async initialCityList({ commit }) {
            const siteContacts = await fetch('/api/contacts')
            commit('setSiteContacts', siteContacts)
        }
    },

in the component:
async created() {
    await this.$store.dispatch("initialCityList");
  },

If I change new Promise .....everything is fine.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RokeAlvo, 2019-11-29
@RokeAlvo

in general figured out, if it will be useful to anyone: it
await fetch()returns the Response
object , respectively, it is required to execute await response.json()or other methods, depending on the type of data received. I draw attention to await: response.json()it returns a Promise, respectively, await is needed
Total:

actions: {
         async initialCityList({ commit }) {
            const siteContacts = await fetch('/api/contacts')
            commit('setSiteContacts',  await siteContacts.json())
        }
    },

When using Axios:
axios.get() returns an object that contains the response body in the data field, respectively, the resulting code:
actions: {
         async initialCityList({ commit }) {
            const siteContacts = await axios.get('/api/contacts')
            commit('setSiteContacts', siteContacts.data)
        }
    },

D
Dmitry, 2019-11-29
@dmtrrr

https://stackoverflow.com/questions/49577394/which...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question