Home > OS >  Best practice to use v-skeleton-loader with Vuex
Best practice to use v-skeleton-loader with Vuex

Time:06-22

I want to make v-skeleton-loder loading when the data from API is not yet fetched. The thing is I use dispatch to call the action.

getSomething(id) {
 this.$store.dispatch("getSomething");
},

Here is my skeleton, and I also called the loading from Vuex using computed property.

<v-skeleton-loader type="table" :loading="loading"></v-skeleton-loader>

I put the loading in my store.js like this

state : {
loading:true}

actions: {
async getSomething(){
 await axios.get(url)
  .then(async () => {
      state.loading = false //after data is fetched
  })
  .catch((err) => {
     console.log(err)
  })
 }
}

This doesn't work and I also don't know how to set the loading value back to true for other skeletons. Or is there any more efficient way to achieve this without using Vuex? Appreciate all help, thanks!

CodePudding user response:

You can set vuex state for loading:

const state = {
  loading: true,
};

const mutations = {
  changeLoadingState(state, loading) {
    state.loading = loading;
  },
},

const actions = {
  setLoadingState({ commit }, loading) {
    commit('changeLoadingState', loading);
  },
}

then dispatch action before and after

getSomething(id) {
  this.$store.dispatch("setLoadingState", true)
  this.$store.dispatch("getSomething");
  this.$store.dispatch("setLoadingState", false)
},

CodePudding user response:

you don't mutate state directly, it is done using mutations.I may have made mistakes in the code. Use it as a concept.

actions: {
async getSomething({commit}){
 commit('setLoading', true)
 axios.get(url)
  .then(() => {
      // do something with data
  })
  .catch((err) => {
     console.log(err)
  })
  .finally(() => {
     commit('setLoading', false)
   })
 }
}

mutations: {
setLoading(state, isLoading) {
state.loading=isLoading
}
}
  • Related