Skip to content

Instantly share code, notes, and snippets.

@codinronan
Created November 29, 2020 03:14
Show Gist options
  • Save codinronan/ece9d65ba92049abb1920e57076fae51 to your computer and use it in GitHub Desktop.
Save codinronan/ece9d65ba92049abb1920e57076fae51 to your computer and use it in GitHub Desktop.
React hook: useAsyncAction
// 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