Created
April 23, 2018 21:16
-
-
Save bovas85/83a06f4dd899caa4a6d3faa566c8a2a5 to your computer and use it in GitHub Desktop.
New Vuex cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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