Skip to content

Instantly share code, notes, and snippets.

@mgutz

mgutz/colors.js

Last active May 30, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@mgutz 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
You can’t perform that action at this time.