Skip to content

Instantly share code, notes, and snippets.

@mikevercoelen
Last active April 16, 2018 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikevercoelen/630ade22b7c49e9caec9c41108886355 to your computer and use it in GitHub Desktop.
Save mikevercoelen/630ade22b7c49e9caec9c41108886355 to your computer and use it in GitHub Desktop.
Less boilerplate for Redux Reducers
function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
}
return state
}
}
import { createReducer } from '../helpers/createReducer'
import { ORDERS_LOAD } from '../constants/ActionTypes'
const initialState = {
data: [],
error: false,
pending: false
}
export default createReducer(initialState, {
[ORDERS_LOAD + '_PENDING']: () => ({
...initialState,
pending: true
}),
[ORDERS_LOAD + '_SUCCESS']: (state, { payload }) => ({
pending: false,
data: payload
}),
[ORDERS_LOAD + '_ERROR']: (state, { error }) => ({
pending: false,
error
})
})
import { ORDERS_LOAD } from '../constants/ActionTypes'
const initialState = {
data: [],
error: false,
pending: false
}
export default function ordersReducer (state = initialState, action) {
switch (action.type) {
case ORDERS_LOAD + '_PENDING':
return {
...state,
error: false,
pending: true
}
case ORDER_LOAD + '_ERROR':
return {
...state,
error: action.error,
pending: false
}
case ORDERS_LOAD + '_SUCCESS':
return {
...state,
data: action.payload,
pending: false
}
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment