Before moving, we should familiarize ourselves with how Redux is written from scratch.
Previously, when we log the store, we see the public interface with three main functionality:
– getState
– dispatch
– subscribe
Let’s try to implement them.
My Store
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function myStore { let store; // private // getter to access function getState() { return store; } return { getState } } export default myStore; |
We hide our store variable in myStore. It is private.
1 2 |
import store from './myStore'; store.getState(); |
Dispatch
Our reducer function gets passed into our constructor.
So we add a reducer parameter.
We create a dispatch function. So by scope, we access the passed in reducer function, and pass in action, and state. Remember in our reducer, we always return the new state. So we reference our state to the returned state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function MyStore(reducer) { let state; function dispatch(action) { state = reducer(state, action); } function getState() { return state; } return { dispatch, getState } } export default MyStore(reducer); |
Notify Subscribers (UI components)
When the state of the store gets changed, we want to notify the UI components. Hence we need these UI components be able to subscribe to our store.
1 2 3 |
store.subscribe(state => { NavComponent.render(state); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function MyStore(reducer) { let state; let listeners = []; function subscribe(listener) { listeners.push(listener); } function dispatch(action) { // validate action has 'type' property state = reducer(state, action); for (let i = 0; i < listeners.length; i++) { listeners[i](); } } return { dispatch, subscribe, getState } } |