Last active
February 15, 2024 17:03
-
-
Save jabney/f135c8377213d6f9a008d3d55db5fd9e to your computer and use it in GitHub Desktop.
micro-redux: a minimal implementation of Redux createStore, with thunkish behavior added in
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
/** | |
* Minimal implementation of Redux createStore, with thunkish behavior. | |
*/ | |
import subject from './micro-subject' // see micro-subject.js gist | |
/** | |
* @template T | |
* @typedef {import('./subject').Subject<T>} Subject | |
*/ | |
/** | |
* @param {(state: any, action: any) => any} reducer | |
* @param {any} [initial] | |
*/ | |
export const createStore = (reducer, initial) => { | |
/** | |
* @type {Subject<void>} | |
*/ | |
const _subject = subject() | |
let state = initial !== undefined ? initial : reducer(undefined, {}) | |
return { | |
/** | |
* Dispatch an action to update the store. | |
*/ | |
dispatch(action) { | |
// Built-in 'thunk' functionality. | |
if (typeof action === 'function') { | |
action(this.dispatch.bind(this), this.getState) | |
} else { | |
state = reducer(state, action) | |
_subject.notify() | |
} | |
}, | |
/** | |
* Get the store's current state. | |
*/ | |
getState() { | |
return state | |
}, | |
/** | |
* Receive notifications when the store is updated. | |
* | |
* @param {() => void} observer | |
* | |
* @returns {() => void} unsubscribe function | |
*/ | |
subscribe(observer) { | |
const unsubscribe = _subject.subscribe(observer) | |
_subject.notify() | |
return unsubscribe | |
} | |
} | |
} | |
export default createStore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment