Created
November 29, 2020 03:14
-
-
Save codinronan/ece9d65ba92049abb1920e57076fae51 to your computer and use it in GitHub Desktop.
React hook: useAsyncAction
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
// The goal here is to demonstrate using a React context as a redux-like reducer-based store. | |
import { useContext } from 'react' | |
import { Store } from '../store' | |
const ACTION_ASYNC_REQUEST_SUFFIX = '@REQUEST' | |
const ACTION_ASYNC_SUCCESS_SUFFIX = '@SUCCESS' | |
const ACTION_ASYNC_FAILURE_SUFFIX = '@FAIL' | |
const ACTION_ASYNC_SUCCESS_METHOD = 'success' | |
const ACTION_ASYNC_FAILURE_METHOD = 'fail' | |
const useAsyncAction = type => { | |
const { dispatch } = useContext(Store) | |
let action = {} | |
action = () => { | |
const actionObj = { | |
type: `${type}${ACTION_ASYNC_REQUEST_SUFFIX}` | |
} | |
return dispatch(actionObj) | |
} | |
action[ACTION_ASYNC_SUCCESS_METHOD] = payload => { | |
const actionObj = { | |
type: `${type}${ACTION_ASYNC_SUCCESS_SUFFIX}`, | |
payload | |
} | |
return dispatch(actionObj) | |
} | |
action[ACTION_ASYNC_FAILURE_METHOD] = err => { | |
const actionObj = { | |
type: `${type}${ACTION_ASYNC_FAILURE_SUFFIX}`, | |
payload: err | |
} | |
return dispatch(actionObj) | |
} | |
return [ action ] | |
} | |
export default useAsyncAction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment