Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
redux-act inspired
const createAction = (type) => {
  const actionCreator = (payload) => ({
    type,
    payload,
  })

  actionCreator.type = type

  return actionCreator
}

const createReducer = (actionHandlers, initialState) => (
  (state = initialState, { type, payload }) => {
    const handler = actionHandlers[type]

    return handler ? handler(state, payload) : state
  }
)

usage:

// Action creator acts both as actionCreator and actionType
export const fetchMany = createAction('FETCH_MANY')


console.log(fetchMany.type) // 'FETCH_MANY'
console.log(fetchMany()) // {type: 'FETCH_MANY', payload: undefined}

// dispatch(fetchMany(payload))


const actionHandlers = {
  [fetchMany.type]: (state, payload) => ({ ...state, ...payload })
}

const initialState = {}

const fooReducer = createReducer(actionHandlers, initialState)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.