Last active
December 24, 2019 17:56
-
-
Save mohdovais/f81b4647e9a5caa5f6c71b9a4a370551 to your computer and use it in GitHub Desktop.
Redux style store with svelte/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
/** | |
* Svelte does not compare objects | |
* https://github.com/sveltejs/svelte/issues/2171 | |
* and therefore store.update notifies subscribers, even if same object is | |
* returned. Otherwise the method could be much simpler: | |
* const dispatch = action => update(state => reducer(state, action)); | |
* | |
* @param {function} reducer | |
* @param {*} initialState | |
*/ | |
export function createStore(reducer, initialState = {}) { | |
const store = writable(initialState); | |
const dispatch = action => { | |
const current_state = get(store); | |
const next_state = reducer(current_state, action); | |
if (current_state !== next_state) { | |
store.set(next_state); | |
} | |
}; | |
return { | |
subscribe: store.subscribe, | |
dispatch | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple Usage