Last active
May 30, 2019 09:05
-
-
Save mgutz/89c0e1b1a447232192783e57ed5c59fc to your computer and use it in GitHub Desktop.
svelte3 actions and getters using nested object store
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 {readable, writable} from 'svelte/store'; | |
// could be its own module | |
const util = { | |
_root: null, | |
// similar to createSelector but instead returns a reactive variable | |
createGetter(store, fn, initialData) { | |
return readable(initialData, set => { | |
store.subscribe(state => set(fn(state, this._root))); | |
}); | |
}, | |
// set the root store | |
setRoot(root) { | |
this._root = root; | |
}, | |
}; | |
//---------------------------------------------------------------------------- | |
// State | |
//---------------------------------------------------------------------------- | |
const initialState = { | |
selected: 'green', | |
colors: { | |
red: '#f00', | |
green: '#0f0', | |
blue: '#00f', | |
}, | |
}; | |
const store = writable(initialState); | |
//---------------------------------------------------------------------------- | |
// Actions | |
//---------------------------------------------------------------------------- | |
// writable publishes updates so no need to be immutable | |
export const add = (k, v) => | |
store.update(state => { | |
state.colors[k] = v; | |
return state; | |
}); | |
export const setSelected = k => | |
store.update(state => { | |
state.selected = k; | |
return state; | |
}); | |
//---------------------------------------------------------------------------- | |
// Getters | |
//---------------------------------------------------------------------------- | |
// usage: {#each $colorsGetter as [k, v]} ... {/each} | |
export const colorsGetter = util.createGetter(store, state => { | |
const result = []; | |
for (const k in state.colors) { | |
// skip red to show filtering | |
if (k === 'red') continue; | |
result.push([k, state.colors[k]]); | |
} | |
return result; | |
}); | |
export default store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think updates need to be immutable since writable publishes new value to subscribers.