I have several pages that I want to retrieve, I have it working but notice that the page loads a bit slow while it is not much data.
How can I set my APIs in vuex store with axios so that it performs better.
Store:
export default {
state: {
homepage: [],
aboutUs: []
},
actions: {
async loadPosts({ commit }) {
// Define urls pages
const urlHomepage = 'https://api.domain.com/homepage';
const urlaboutUs = 'https://api.domain.com/aboutUs';
// Responses pages
const responseHomepage = await this.$axios.get(urlHomepage);
const responseaboutUs = await this.$axios.get(urlaboutUs);
// variables pages
this.homepage = responseHomepage.data
this.aboutUs = responseaboutUs.data
// mutations pages
commit('SET_HOMEPAGE', this.homepage)
commit('SET_aboutUs', this.aboutUs)
}
},
mutations: {
SET_HOMEPAGE (state, homepage) {
state.homepage = homepage;
},
SET_aboutUs (state, aboutUs) {
state.aboutUs = aboutUs;
}
}
};
And I use this in my page like:
import {mapState} from 'vuex';
export default {
name: 'Home',
mounted() {
this.$store.dispatch('loadPosts')
},
computed: {
...mapState([
'homepage'
])
}
}
By adding:
{{homepage}}
Is there a better way to store multiple API urls? I'm using Nuxt.js.
You could speed things up significantly (especially for more than 2 pages) by running the async calls simultaneously instead of running one only after the other is finished:
Version 1
// Execute async immediately and store the promises
const pH = this.$axios.get(urlHomepage);
const pA = this.$axios.get(urlaboutUs);
// Await them all at once instead of individually
const [rH, rA] = await Promise.all([pH, pA]);
Or another way of writing this:
Version 2
const [rH, rA] = await Promise.all([
this.$axios.get(urlHomepage),
this.$axios.get(urlaboutUs)
]);
The results array order will be the same as the called order
Then store the results:
// variables pages
this.homepage = rH.data
this.aboutUs = rA.data
// mutations pages
commit('SET_HOMEPAGE', this.homepage)
commit('SET_aboutUs', this.aboutUs)