Created
January 7, 2020 15:34
-
-
Save valmassoi/72dbd47d18c335dcab440e444bc58a9a to your computer and use it in GitHub Desktop.
redux createStore from scratch
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
// https://egghead.io/lessons/react-redux-implementing-store-from-scratch | |
const createStore = (reducer) => { | |
let state; | |
let listeners = []; | |
const getState = () => state; | |
const dispatch = (action) => { | |
// calculate new state | |
state = reducer(state, action) | |
// notify subscribers know of state change | |
listeners.forEach(listener => listener()); | |
} | |
const subscribe = (listener) => { | |
// keep list of subscribers | |
listeners.push(listener); | |
// unsubscribe by calling again | |
return () => { | |
listeners = listeners.filter(l => l !== listener); | |
} | |
} | |
// init state | |
dispatch({}); | |
return { getState, dispatch, subscribe }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment