Last active
July 9, 2018 18:49
-
-
Save jhamberg/075be0b31d626a6aa13e20394f975a35 to your computer and use it in GitHub Desktop.
Redux (flux) in 12 lines of code with an example.
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 => { | |
const subscribers = []; | |
let state = reducer(undefined, {type: "__init"}); | |
return { | |
dispatch: action => { | |
state = reducer(state, action); | |
subscribers.forEach(fun => fun()); | |
}, | |
subscribe: fun => subscribers.push(fun), | |
getState: () => state | |
} | |
} |
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
// Create a simple counter reducer | |
const counterReducer = (state = 0, action) => { | |
switch (action.type) { | |
case "INCREMENT": return state + 1; | |
case "DECREMENT": return state - 1; | |
} | |
return state; // This is important so __init works | |
}; | |
// Initialize store and dispatch | |
const store = createStore(counterReducer); | |
store.dispatch({type: "INCREMENT"}); | |
store.dispatch({type: "INCREMENT"}); | |
console.log(store.getState()); // Prints "2" | |
// Subscriber example | |
const render = () => console.log(`counter: ${store.getState()}`); | |
store.subscribe(render); | |
store.dispatch({type: "INCREMENT"}); // Prints "counter: 3" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment