-
-
Save radum/7132834a5929c499c69321f8e7b96877 to your computer and use it in GitHub Desktop.
A mini redux implementation
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
/* | |
You need node 6.9 or later. | |
Run with: | |
node redux-mini.js --harmony | |
Want a more in depth explanation of how things works? Read the blog post I have written about it here: | |
http://blog.jakoblind.no/2017/03/13/learn-redux-by-coding-a-mini-redux/ | |
*/ | |
/* | |
Mini Redux implementation | |
*/ | |
function createStore(reducer, initialState) { | |
var currentReducer = reducer; | |
var currentState = initialState; | |
var listener = () => {}; | |
return { | |
dispatch(action) { | |
currentState = currentReducer(currentState, action); | |
listener() | |
return action; | |
}, | |
subscribe(newListener) { | |
listener = newListener; | |
}, | |
getState() { | |
return currentState; | |
} | |
}; | |
} | |
/* | |
Example usage of our Mini Redux. | |
Copy pasted from the Redux official github page: https://github.com/reactjs/redux#the-gist | |
*/ | |
function counter(state = 0, action) { | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1 | |
case 'DECREMENT': | |
return state - 1 | |
default: | |
return state | |
} | |
} | |
let store = createStore(counter) | |
store.subscribe(() => | |
console.log(store.getState()) | |
) | |
store.dispatch({ type: 'INCREMENT' }) | |
store.dispatch({ type: 'INCREMENT' }) | |
store.dispatch({ type: 'DECREMENT' }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment