Skip to content

Instantly share code, notes, and snippets.

@tkovs
Created August 16, 2019 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkovs/fddd790da831fc532194c61f012eba0f to your computer and use it in GitHub Desktop.
Save tkovs/fddd790da831fc532194c61f012eba0f to your computer and use it in GitHub Desktop.
Create store basic implementation
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 }
}
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
const store = createStore(counter)
const renderToPage = () => {
document.body.innerText = store.getState()
}
const renderToConsole = () => {
console.log(store.getState())
}
store.subscribe(renderToPage)
renderToPage()
store.subscribe(renderToConsole)
renderToConsole()
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