Last active
April 16, 2018 10:47
-
-
Save mikevercoelen/630ade22b7c49e9caec9c41108886355 to your computer and use it in GitHub Desktop.
Less boilerplate for Redux Reducers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createReducer(initialState, handlers) { | |
return function reducer(state = initialState, action) { | |
if (handlers.hasOwnProperty(action.type)) { | |
return handlers[action.type](state, action) | |
} | |
return state | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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