Created
February 29, 2016 17:12
-
-
Save bloodyowl/babd93183ff8581724fe to your computer and use it in GitHub Desktop.
redux in 14 lines of code
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
const store = createStore((state = { counter: 0 }, action) => { | |
switch(action.type) { | |
case "INCREMENT": | |
return { counter: state.counter + 1 } | |
case "DECREMENT": | |
return { counter: state.counter - 1 } | |
default: | |
return state | |
} | |
}) | |
store.dispatch({ type: "INCREMENT" }) | |
store.dispatch({ type: "INCREMENT" }) | |
console.log(store.getState()) |
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
const createStore = (reducer, state = reducer(undefined, { type: "@@INIT" })) => { | |
const subscribers = new Set() | |
return { | |
dispatch: (action) => { | |
state = reducer(state, action) | |
subscribers.forEach(func => func()) | |
}, | |
subscribe: (func) => { | |
subscribers.add(func) | |
return () => subscribers.delete(func) | |
}, | |
getState: () => state | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment