Created
April 10, 2018 11:29
-
-
Save bovas85/ebea97fcf97bc4d97625026a21d9ddfe to your computer and use it in GitHub Desktop.
Cache API calls in Vuex on nuxtServerInit
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 axios from "axios"; | |
import Config from "~/assets/config.js"; | |
const api = axios.create(); | |
let arr = []; | |
let count = 0; | |
/** | |
* This is the secret sauce. | |
* If the data being requested is cached, subsequent API calls will not be made | |
* During a nuxt generate, nuxtServerInit will be called for every page | |
* Because of this caching, the API calls will only be done once | |
* | |
*/ | |
function cachePosts () { | |
if (!arr.length || count == 3) { | |
count = 0; | |
console.log("Running API calls, no cache"); | |
// if cache doesn't exist, get the data from the API and cache it | |
let home = api | |
.request(Config.wpDomain + Config.api.homePage) | |
.then(res => { | |
console.log("home"); | |
return res.data; | |
}) | |
.catch(err => console.log(err)); | |
let destinations = api | |
.request(Config.wpDomain + Config.api.destinations) | |
.then(res => { | |
console.log("destinations"); | |
return res.data; | |
}) | |
.catch(err => console.log(err)); | |
return Promise.all([home, destinations]) | |
.then(values => { | |
arr = values; | |
return values; | |
}) | |
.catch(err => console.log(err)); | |
} else { | |
console.log("Using cached API calls"); | |
count++; | |
console.log(count); | |
return arr; | |
} | |
} | |
const createStore = () => { | |
return new Vuex.Store({ | |
state: { | |
destinations: [], | |
homePage: [] | |
}, | |
mutations: { | |
setDestinations (state, obj) { | |
// sorting alphabetically | |
if (obj != null) { | |
try { | |
let filteredDestinations = obj.sort(function (a, b) { | |
return a.slug.localeCompare(b.slug); | |
}); | |
state.destinations = filteredDestinations; | |
} catch (e) { | |
console.log("filter error on setDestinations", e); | |
} | |
} | |
}, | |
setHomePage (state, obj) { | |
state.homePage = obj; | |
} | |
}, | |
actions: { | |
async nuxtServerInit ({ commit }, { context }) { | |
const cache = await cachePosts(); | |
commit("setHomePage", cache[0]); | |
commit("setDestinations", cache[1]); | |
} | |
} | |
}); | |
}; | |
export default createStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment