-
-
Save slugbyte/ca0731b42c27cce67ef1c344d37666f0 to your computer and use it in GitHub Desktop.
Implementing Redux Store 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
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'}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment