Created
July 4, 2020 12:51
-
-
Save iiisoni/9476de109fe1147fb56752f130590309 to your computer and use it in GitHub Desktop.
Redux utils
This file contains 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 errorTypeDetailMap from '$CONFIG/errorTypeDetailMap' | |
const errorTypeDetailMap = {} | |
function makeActionByType(actionName, type) { | |
const typeValueMap = { | |
success : '_SUCCESS', | |
failure : '_FAILURE' | |
} | |
return { | |
type : `${actionName}${typeValueMap[type]}` | |
} | |
} | |
export function makeActions(actionName) { | |
return { | |
defaultAction(options = {}) { | |
return { | |
type : actionName, | |
...options | |
} | |
}, | |
successAction(response) { | |
return { | |
...makeActionByType(actionName, 'success'), | |
response | |
} | |
}, | |
failureAction(error = errorTypeDetailMap.generic) { | |
return { | |
...makeActionByType(actionName, 'failure'), | |
error | |
} | |
} | |
} | |
} | |
const defaultState = { | |
isFetching : true, | |
error : '' | |
} | |
export function makeReducer({ | |
actionName, | |
additionalActions, | |
initialState = defaultState, | |
shouldMergeDefaultStates = false | |
}) { | |
const mergedState = shouldMergeDefaultStates | |
? { | |
...defaultState, | |
...initialState | |
} : initialState | |
return function (state = mergedState, action) { | |
const moreActions = additionalActions ? additionalActions(state, action) : {} | |
const options = { | |
[actionName] : () => ({ | |
...state, | |
isFetching : true | |
}), | |
[makeActionByType(actionName, 'failure').type] : () => ({ | |
...state, | |
isFetching : false, | |
error : action.error | |
}), | |
[makeActionByType(actionName, 'success').type] : () => ({ | |
...state, | |
error : '', | |
isFetching : false, | |
response : action.response | |
}), | |
...moreActions | |
} | |
return action.type && options[action.type] ? options[action.type]() : state | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment