Last active
February 26, 2018 17:40
-
-
Save theikkila/198a32c9180171f00d9acae098d4b351 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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