DEV Community

Discussion on: Structuring store with the right feet using vue/vuex

Collapse
 
chrismichael profile image
Chris Michael

❤️ Very grateful for your comments ..

I must mention that we can improve our GET_DATA action by adding the setTimeout function, this will help us to execute the function in a time interval and load our data at that time.

GET_DATA({commit}){
  A.get(API_URL_ENDPOINT).then((res) =>{
    commit('SET_DATA' , res.data);
    setTimeout(() =>{
      commit('IS_LOADING' , false);
    } , 1000)
  }).catch((err) =>{
      console.error(err)
    });
  }
Collapse
 
tobymosque profile image
Tobias Mesquita

great article, but i think actions who does async tasks would return a promise.

GET_DATA({commit}){
  return A.get(API_URL_ENDPOINT).then((res) =>{
    commit('SET_DATA' , res.data);
    setTimeout(() =>{
      commit('IS_LOADING' , false);
    } , 1000)
  }).catch((err) =>{
    console.error(err)
  });
}

anyway, i think IS_LOADING would be set to false, even if the http request throws a error.

async GET_DATA({commit}){
  try {
    const { data } = await A.get(API_URL_ENDPOINT)
    commit('SET_DATA' , res.data)
  } catch () {
    console.error(err)
  } finally () {
    setTimeout(() =>commit('IS_LOADING' , false), 1000)
  }
}