Skip to content

Instantly share code, notes, and snippets.

@mgutz
Last active May 30, 2019 09:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgutz/89c0e1b1a447232192783e57ed5c59fc to your computer and use it in GitHub Desktop.
Save mgutz/89c0e1b1a447232192783e57ed5c59fc to your computer and use it in GitHub Desktop.
svelte3 actions and getters using nested object store
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;
@mgutz
Copy link
Author

mgutz commented May 30, 2019

I don't think updates need to be immutable since writable publishes new value to subscribers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment