MK01111000
MK01111000

Reputation: 822

How to check if JSON data is loaded

I use axios to fetch my JSON file en vuex for using the fetched data over multiple components. The thing is that my page renders before all data is loaded. The following works because I delayed the rendering by 2 seconds, without this timeout it would result in an error. I would like to do this the proper way but am not sure how to do it.

STORE.JS

Vue.use(Vuex);    
const store = new Vuex.Store({
    state: {
        poss: null
    },
    getters: {
        NAME: state => {
            return state.name
        },
        POSS: state => {
            return state.poss
        }
    },
    mutations: {
        SET_POSS : (state,payload) => {
          state.poss = payload
        },
        ADD_POSS : (state,payload) => {
          state.poss.push(payload)
        },
      },
      actions:{
       GET_POSS : async (context,payload) => {
          let { data } = await axios.get("json/poss.json")
          context.commit('SET_POSS',data)
       },
       SAVE_POSS : async (context,payload) => {
          let { data } = await axios.post("json/poss.json")
          context.commit('ADD_POSS',payload)
       }
    }
});

COMPONENT.VUE

module.exports = {          
        mounted:function(){
            var self = this;
            setTimeout(function () {
                self.mkPageload()
            }, 2000);
       },
       methods: {
            mkPageload: function(){ 
                let positions = this.$store.getters.POSS.pos            
                Object.keys(positions).forEach(key => { 
                   // rendering
                }
            }
       }
}

The desired result is that the page is only rendered after all data from the JSON file has been loaded.

Upvotes: 1

Views: 623

Answers (1)

dreijntjens
dreijntjens

Reputation: 4825

There are several ways to solve this.

  • You could use wait / async in your component.

    async mounted () {
       await userStore.getAll()
       // access getter and render
    },
    
  • Your could watch vuex variable like (could be done without async but I like to add them)

    async mounted () {
       await userStore.getAll()
    },
    computed: {
    ...mapGetters('users')
    }, 
    watch: {
        users(newValue, oldValue) {
           ....
           // render
        }
    }
    

dont'forget to import the mapGetters: https://vuex.vuejs.org/guide/getters.html

Upvotes: 2

Related Questions