Skip to content

Instantly share code, notes, and snippets.

@bovas85
Created April 23, 2018 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bovas85/83a06f4dd899caa4a6d3faa566c8a2a5 to your computer and use it in GitHub Desktop.
Save bovas85/83a06f4dd899caa4a6d3faa566c8a2a5 to your computer and use it in GitHub Desktop.
New Vuex cache
import Vuex from "vuex";
import Config from "~/assets/config.js";
let arr = [];
let count = 0;
const createStore = () => {
return new Vuex.Store({
...
actions: {
async nuxtServerInit ({ commit }, { app }) {
/**
* This is the secret sauce.
* If the data being requested is cached, subsequent API calls will not be made
* Also, if using nuxt generate, nuxtServerInit will be called for every page
* Because of this caching, the API calls will only be done once
*/
if (!arr.length || count == 3) {
count = 0;
arr = [];
let home = await app.$axios.get(
Config.wpDomain + Config.api.homePage
);
let destinations = await app.$axios.get(
Config.wpDomain + Config.api.destinations
);
let continents = await app.$axios.get(
Config.wpDomain + Config.api.continents
);
let blogs = await app.$axios.get(
Config.wpDomain + Config.api.journal
);
arr.push(home.data);
arr.push(destinations.data);
arr.push(continents.data);
arr.push(blogs.data);
commit("setHomePage", home.data);
// console.log("============= Server Init API calls =============");
// console.log("home");
commit("setDestinations", destinations.data);
// console.log("destinations");
commit("setContinents", continents.data);
// console.log("continents");
commit("setBlogs", blogs.data);
// console.log("blogs");
} else {
commit("setHomePage", arr[0]);
commit("setDestinations", arr[1]);
commit("setContinents", arr[2]);
commit("setBlogs", arr[3]);
count++;
}
}
}
});
};
export default createStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment