Skip to content

Instantly share code, notes, and snippets.

@bovas85

bovas85/store.js

Created Apr 10, 2018
Embed
What would you like to do?
Cache API calls in Vuex on nuxtServerInit
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
You can’t perform that action at this time.