Skip to content

Instantly share code, notes, and snippets.

@rickyalmeidadev
Created July 4, 2021 09:18
Show Gist options
  • Save rickyalmeidadev/6c2b5245be8c0da7e00d11ae6a84d1ba to your computer and use it in GitHub Desktop.
Save rickyalmeidadev/6c2b5245be8c0da7e00d11ae6a84d1ba to your computer and use it in GitHub Desktop.
Simple implementation of Redux
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.splice(listeners.indexOf(listener), 1)
}
}
dispatch({})
return { getState, dispatch, subscribe }
}
const reducer = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment