Skip to content

Instantly share code, notes, and snippets.

@xmas
Created November 29, 2016 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmas/4c0ec3a682df6223ba79f30311b741e7 to your computer and use it in GitHub Desktop.
Save xmas/4c0ec3a682df6223ba79f30311b741e7 to your computer and use it in GitHub Desktop.
Vue localForage plugin and associated helpers
const app = new Vue({
store,
mounted : function () {
const warmCache = 1000 * 60 * 15;
for (var i = 0; i < rezza_providers.length; i++) {
let provider = rezza_providers[i];
let now = new Date();
localforage.getItem(provider.dbKey+'.updated')
.then( (lastUpdatedAt) => {
let elapsed = now - lastUpdatedAt;
if (elapsed > warmCache || lastUpdatedAt === undefined) {
provider.loadFunction();
} else {
localforage.getItem(provider.dbKey)
.then( (cachedValue) => {
store.dispatch(provider.storeAction, cachedValue);
})
.then (() => {
provider.loadFunction();
})
.catch(function(reason) {
console.log('failed to return from getting '+provider.dbKey);
console.log(reason);
});
}
})
.catch(function(reason) {
console.log('failed to return from getting updated date on '+provider.dbKey);
console.log(reason);
});
}
}
}).$mount('#app')
// provider defined below
let rezza_providers = [data_loader];
const foragePlugin = store => {
store.subscribe((mutation, state) => {
let provider = _.find(rezza_providers, ['mutationKey', mutation.type]);
if (provider) {
localforage.setItem(provider.dbKey, state[provider.storeKey])
.then( (value) => {
console.log('data successfully updated for: '+provider.dbKey);
let now = new Date();
localforage.setItem(provider.dbKey+'.updated', now)
.then( (value) => {
console.log('data successfully updated date for: '+provider.dbKey);
})
.catch(function(reason) {
console.log('failed to return from setting updated date '+provider.dbKey);
console.log(reason);
});
})
.catch(function(reason) {
console.log('failed to return from setting on '+provider.dbKey);
console.log(reason);
});
}
});
}
https://github.com/localForage/localForage
const data_loader = {
'mutationKey' : 'SET_DATA',
'storeAction' : 'LOAD_DATA',
'dbKey' : 'data',
'storeKey': 'tables',
'loadFunction' : function () {
//AJAX LOAD HERE THAT CALLS:
//store.dispatch('LOAD_DATA', data.table.dataTableList);
}
}
const store = new Vuex.Store({
plugins: [foragePlugin],
state: {
tables: {},
},
mutations: {
SET_DATA: (state, { new_tables }) => {
for (var table_key in new_tables) {
Vue.set(state.tables, table_key, new_tables[table_key])
}
}
},
actions: {
LOAD_DATA (context, new_data) {
var new_tables = _.keyBy(new_data, 'id');
context.commit('SET_DATA', {new_tables});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment