Riza Khan
Riza Khan

Reputation: 3158

Theory: Axios Calls (Specifically for VueJS)

On component mount(), Axios fetches information from the back end. On a production site, where the user is going back and forth between routes it would be inefficient to make the same call again and again when the data is already in state.

How do the pros design their VueJS apps so that unnecessary Axios calls are not made?

Thank you,

Upvotes: 1

Views: 102

Answers (1)

Phil
Phil

Reputation: 164900

If the data is central to your application and being stored in Vuex (assuming that's what you mean by "state"), why not just load it where you initialise your store?

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'wherever'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    centralData: {}
  },
  mutations: {
    setCentralData (state, centralData) {
      state.centralData = centralData
    }
  },
  actions: {
    async loadCentralData ({ commit }) {
      const { data } = await axios.get('/backend')
      commit('setCentralData', data)
    }
  }
}

// initialise
export const init = store.dispatch('loadCentralData')

export default store

If you need to wait for the dispatch to complete before (for example) mounting your root Vue instance, you can use the init promise

import Vue from 'vue'
import router from 'path/to/router'
import store, { init } from 'path/to/store'

init.then(() => {
  new Vue({
    store,
    router,
    // etc
  }).$mount('#app')
})

You can import and use the init promise anywhere in order to wait for the data to load.

Upvotes: 2

Related Questions