const counter = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } /* Store implementation from scratch */ const createStore = (reducer) => { let state; let listeners = []; const getState = () => state; const dispatch = (action) => { state = reducer(state, action); listeners.forEach(listener => listener()); }; const subscribe = (listener) => { listeners.push(listener); return () => { listeners = listeners.filter(l => l !== listener); }; }; dispatch({}); return { getState, dispatch, subscribe }; }; // Call createStore with // counter as the reducer // manages the state update const store = createStore(counter); /* The store binds together the three principles of Redux. It holds the current application state object, it lets you dispatch actions and when you create it you need to specify the reducer that tells how state is updated with actions. */ // Retrives the current state of the // redux store console.log(store.getState()); // Lets you dispatch actions // and change the state of your app store.dispatch({type: 'INCREMENT'}) console.log(store.getState()); const render = () => { document.body.innerText = store.getState(); } /* Lets you register a callback The redux store will anytime an action has been dispatched so you can update the UI to reflect the current application state */ store.subscribe(render); render(); // Dispatch event with click document.addEventListener('click', () => { store.dispatch({type: 'INCREMENT'}); })