Skip to content

Instantly share code, notes, and snippets.

@theikkila
Last active February 26, 2018 17:40
Show Gist options
  • Save theikkila/198a32c9180171f00d9acae098d4b351 to your computer and use it in GitHub Desktop.
Save theikkila/198a32c9180171f00d9acae098d4b351 to your computer and use it in GitHub Desktop.
function Atom(initialState) {
this.state = initialState
this.cbs = []
this.on = (cb) => this.cbs.push(cb)
this.swap = (f, a) => {
this.state = f(this.state, a)
this.cbs.forEach(cb => cb(this.state))
return this.state
}
return this
}
const createStore = (reducer, initialState) => {
const atom = new Atom(initialState)
this.dispatch = action => atom.swap(reducer, action)
this.on = f => {
f(atom.state)
atom.on(f)
}
return this
}
const root = (state, action) => {
switch (action.type) {
case "INC":
state.counter++;
return state;
case "DEC":
state.counter--;
return state;
default:
return state
}
}
const store = createStore(root, {counter: 0})
store.on(s => console.log("RENDER REACT TREE NOW WITH STATE:", s))
store.dispatch({type: "INC"})
store.dispatch({type: "INC"})
store.dispatch({type: "DEC"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment