Skip to content

Instantly share code, notes, and snippets.

@mohdovais
Last active December 24, 2019 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohdovais/f81b4647e9a5caa5f6c71b9a4a370551 to your computer and use it in GitHub Desktop.
Save mohdovais/f81b4647e9a5caa5f6c71b9a4a370551 to your computer and use it in GitHub Desktop.
Redux style store with svelte/store
/**
* 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
};
}
@mohdovais
Copy link
Author

Simple Usage

<script>
import { createStore } from './svelte-store.js';
const ACTION_INCREASE = 0;
/* const ACTION_DECREASE = 1; */

function storeReducer(state, action){
    switch(action){
        case ACTION_INCREASE:
            return state + 1;
    }

    return state;
}

const store = createStore(storeReducer, 1);
store.dispatch(ACTION_INCREASE);
</script>

<div>value is {$store}</div>

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