Skip to content

Instantly share code, notes, and snippets.

@agrcrobles
Forked from bloodyowl/redux-light-example.js
Created September 10, 2017 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agrcrobles/e54073849b5c4642803dc005836e97fe to your computer and use it in GitHub Desktop.
Save agrcrobles/e54073849b5c4642803dc005836e97fe to your computer and use it in GitHub Desktop.
redux in 14 lines of code
const store = createStore((state = { counter: 0 }, action) => {
switch(action.type) {
case "INCREMENT":
return { counter: state.counter + 1 }
case "DECREMENT":
return { counter: state.counter - 1 }
default:
return state
}
})
store.dispatch({ type: "INCREMENT" })
store.dispatch({ type: "INCREMENT" })
console.log(store.getState())
const createStore = (reducer, state = reducer(undefined, { type: "@@INIT" })) => {
const subscribers = new Set()
return {
dispatch: (action) => {
state = reducer(state, action)
subscribers.forEach(func => func())
},
subscribe: (func) => {
subscribers.add(func)
return () => subscribers.delete(func)
},
getState: () => state
}
}
@agrcrobles
Copy link
Author

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment