Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxtjs async await in a page doesnt work on page refresh

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?

like image 863
Geoff Avatar asked Jun 03 '18 06:06

Geoff


1 Answers

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);
  }
}
like image 88
Rahmat Aligos Avatar answered Sep 20 '22 19:09

Rahmat Aligos