Skip to content

Instantly share code, notes, and snippets.

@davestewart
Last active August 11, 2020 16:16
Show Gist options
  • Save davestewart/494a3da311af89501ea5c8c79fedf070 to your computer and use it in GitHub Desktop.
Save davestewart/494a3da311af89501ea5c8c79fedf070 to your computer and use it in GitHub Desktop.
Vue JS local storage plugin. Hydrates modules from local storage on load, and saves state on each commit
const storage = window.localStorage
/**
* Storage helper to load, save and remove state from local storage
*
* @param {string} key
*/
function Storage (key = 'vuex') {
Object.assign(this, {
/**
* Load and return local data
*
* @returns {Object}
*/
load () {
return JSON.parse(storage.getItem(key) || '{}')
},
/**
* Hydrate initial Vuex modules from local storage
*
* To hydrate custom classes within each module, add a custom hydrate() method
* to each module's exported definition, and modify the passed state as required
*
* @param {Object} modules The hash of Vuex modules
* @returns {Object}
*/
hydrate (modules) {
const values = this.load()
Object.keys(modules).forEach(name => {
const module = modules[name]
if ('state' in module && name in values) {
if (module['hydrate'] instanceof Function) {
values[name] = module.hydrate(values[name])
}
Object.assign(module.state, values[name])
}
})
return modules
},
/**
* Vuex mutation handler; assign to Store plugins array
*
* @param {Object} store The store to save to local storage
*/
save (store) {
store.subscribe((mutation, state) => {
storage.setItem(key, JSON.stringify(state))
})
},
/**
* Clear local storage data
*/
clear () {
storage.clear()
},
})
}
export default Storage
import Car from 'models/Car'
import Offer from 'models/Offer'
function hydrate (state) {
if (state.car) {
state.car = new Car(state.car._data)
}
if (state.offers) {
state.offers.map(offer => new Offer(offer._data))
}
}
export default{
hydrate, // add a custom hydrate function per module
state: { ... },
mutations: { ... },
getters: { ... },
actions: { ... },
}
const storage = new Storage()
const store = new Vuex.Store({
plugins: [storage.save],
modules: storage.hydrate({
user,
parameters,
results,
application,
account,
settings,
}),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment