Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Last active December 20, 2021 13:33
Show Gist options
  • Save danieljpgo/bf4aa4839eabb3a0bea9bef6fa2e3da8 to your computer and use it in GitHub Desktop.
Save danieljpgo/bf4aa4839eabb3a0bea9bef6fa2e3da8 to your computer and use it in GitHub Desktop.
function asyncReducer(state, action) {
switch (action.type) {
case 'pending': {
return {...state, status: 'pending', data: null, error: null}
}
case 'resolved': {
return {...state, status: 'resolved', data: action.data, error: null}
}
case 'rejected': {
return {...state, status: 'rejected', data: null, error: action.error}
}
default: {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
export function useAsync(initialState) {
const [state, unsafeDispatch] = React.useReducer(asyncReducer, {
status: 'idle',
data: null,
error: null,
...initialState,
})
const dispatch = useSafeDispatch(unsafeDispatch)
const run = React.useCallback(
promise => {
dispatch({type: 'pending'})
promise.then(
data => {
dispatch({type: 'resolved', data})
},
error => {
dispatch({type: 'rejected', error})
},
)
},
[dispatch],
)
return {...state, run}
}
@danieljpgo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment