Last active
February 18, 2020 14:14
-
-
Save sbycrosz/361b326ee2570d93f6f609745f451114 to your computer and use it in GitHub Desktop.
SimpleReducer_ErrorReducer.js
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
// api/errorReducer.js | |
export const errorReducer = (state = {}, action) => { | |
const { type, payload } = action; | |
const matches = /(.*)_(REQUEST|FAILURE)/.exec(type); | |
// not a *_REQUEST / *_FAILURE actions, so we ignore them | |
if (!matches) return state; | |
const [, requestName, requestState] = matches; | |
return { | |
...state, | |
// Store errorMessage | |
// e.g. stores errorMessage when receiving GET_TODOS_FAILURE | |
// else clear errorMessage when receiving GET_TODOS_REQUEST | |
[requestName]: requestState === 'FAILURE' ? payload.message : '', | |
}; | |
}; | |
// api/selectors.js | |
import _ from 'lodash'; | |
export const createErrorMessageSelector = (actions) => (state) => { | |
// returns the first error messages for actions | |
// * We assume when any request fails on a page that | |
// requires multiple API calls, we shows the first error | |
return _(actions) | |
.map((action) => _.get(state, `api.error.${action}`)) | |
.compact() | |
.first() || ''; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment