Nuxtjs async await in a page doesnt work on page refresh

天大地大妈咪最大 提交于 2020-07-20 14:03:54

问题


Am trying to fetch data in the fetch method of my page using vuex and nuxt js but whenever a person refreshes the page it fails but works when i navigate through nuxt navigation

So in my page i have

    fetch ({ store, params }) {
        store.dispatch('getJobspecialisims')
    },

   //IVE ALSO TRIED ASYNC
     async asyncData (context) {
        await context.store.dispatch('getJobspecialisims');
    },

SO in my vuex action i have

   async getJobspecialisims({commit}){
      await axios.get(process.env.baseUrl+'/job-specialisims').then((res)=>{
        commit(types.SET_JOB_SPECIALISIMS, res.data.data)
      },(err)=>{
           console.log("an error occured ", err);
    });
  },

Now on my component where am fetching the records

<div>
  <li v-for="(specialisim) in $store.getters.jobspecialisims">
    <!-DO STUFF HERE->   
 </li>

The http request is nver sent when a person refreshes the browser

Where am i going wrong? I would prefer the async await method. I uderstand that it returns a promise but i have no idea on how to know when the promise has resolved. Thepage should always await untill the data has been completely ffetched hence ive called the fetch or asyncdata method in my page

What else do i need to add or amend?


回答1:


For async actions, you need to put return before dispatch when you call it inside fetch or asyncData:

fetch ({ store, params }) {
  // store.dispatch('getJobspecialisims')
  return store.dispatch('getJobspecialisims')
},

Source for this answer: Problem: Vuex actions, dispatch from page

Anyway, I still don't understand why you used await with then. If I, I will use async await like this:

async getJobspecialisims({ commit }) {
  const res = await axios.get(YOUR_URL);
  if (!res.error) {
    commit("getJobspecialisims", res.data.data);
  } else {
    console.log(res.error);
  }
}


来源:https://stackoverflow.com/questions/50663868/nuxtjs-async-await-in-a-page-doesnt-work-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!