Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TryingToImprove/ff2e29d6f555a3eec047914c54e6c0f8 to your computer and use it in GitHub Desktop.
Save TryingToImprove/ff2e29d6f555a3eec047914c54e6c0f8 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, action) => {
    const handler = actionHandlers[action.type]

    return handler ? handler(state, action) : 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, action) => ({ ...state, ...action.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