Skip to content

Instantly share code, notes, and snippets.

@williamoliveira
Last active December 10, 2016 19:03
Show Gist options
  • Save williamoliveira/c4e1f7c49823dcd1fa8c7aa08b08db1d to your computer and use it in GitHub Desktop.
Save williamoliveira/c4e1f7c49823dcd1fa8c7aa08b08db1d to your computer and use it in GitHub Desktop.
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