5
votes

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
The http request is nver sent when a person refreshes the browser is nuxt.js or the browser caching? Did you use the dev tools in the browser (network tab) and see if you have cached results in there? I'm not sure how to check cache settings in nuxt.js but you could start with the browser.HMR
there are no cached results ive checkedGeoff

1 Answers

15
votes

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);
  }
}