Skip to content

Instantly share code, notes, and snippets.

@wilcorrea
Created August 9, 2019 02:00
Show Gist options
  • Save wilcorrea/b6397e27ba081ccf0239ed6864435315 to your computer and use it in GitHub Desktop.
Save wilcorrea/b6397e27ba081ccf0239ed6864435315 to your computer and use it in GitHub Desktop.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
/**
* @interface StoreState
*/
export interface StoreState {
[key: string]: any
}
/**
* @interface StoreOptions
*/
export interface StoreOptions {
state: StoreState,
mutations: any
}
/**
* @interface StoreObservable
*/
export interface StoreObservable {
state: StoreState,
commit: Function
}
/**
* Helper to create dynamic stores
* Useful to reduce boilerplate.. simple and functional
* Besides the store is standalone and works fine in a lot of places
* @param {StoreOptions} options
* @returns {StoreObservable}
*/
export default (options: StoreOptions): StoreObservable => {
const { state, mutations } = options
return {
state: Vue.observable(state),
commit (mutation: any, ...args: any) {
mutations[mutation](state, ...args)
}
}
}
import $store from 'src/app/Util/store'
import $database from './database'
import { primaryKey } from 'src/settings/schema'
const store = $store({
// the states of store
// ex.: $store.state.records
state: {
records: []
},
// the mutations to call with commit
// ex.: $store.commit('updateRecords', [])
mutations: {
/**
* @param {StoreState} state
* @param {Array} records
*/
updateRecords (state, records) {
state.records = records
$database.setItem('data', state.records)
},
/**
* @param {StoreState} state
* @param {Object} record
*/
updateRecord (state, record) {
const index = state.records.findIndex((item) => item[primaryKey] === record[primaryKey])
state.records.splice(index, 1, record)
$database.setItem('data', state.records)
}
}
})
export default store
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment