Skip to content

Instantly share code, notes, and snippets.

@csenio
Created October 28, 2019 14:49
Show Gist options
  • Save csenio/ac6854736485351a71395f8d9c7360b0 to your computer and use it in GitHub Desktop.
Save csenio/ac6854736485351a71395f8d9c7360b0 to your computer and use it in GitHub Desktop.
import {useReducer, useCallback} from 'react'
import useIsMounted from './useIsMounted'
function useStatus() {
const isMounted = useIsMounted()
const [{status, error}, setState] = useReducer((s, a) => ({...s, ...a}), {
status: 'rest',
error: null,
})
const safeSetState = useCallback((...args) => (isMounted.current ? setState(...args) : null), [
isMounted,
])
const isLoading = status === 'pending'
const isSuccess = status === 'success'
const isRejected = status === 'rejected'
return [{isLoading, isSuccess, isRejected, error}, safeSetState]
}
export default useStatus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment