Last active
September 8, 2020 15:25
-
-
Save akramsaouri/7688bb7a0a9b11834925004f0bd6a28a to your computer and use it in GitHub Desktop.
⚛️ No more isLoading or hasErrored
This file contains hidden or 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
// @flow | |
import { useReducer } from 'react' | |
type AllowedStatus = 'idle' | 'processing' | 'error' | 'success' | |
const alllowedStatus = ['idle', 'processing', 'error', 'success'] | |
type Status = {| | |
state: AllowedStatus, | |
message?: string, | |
|} | |
const initialState = { | |
state: 'idle', | |
message: '', | |
} | |
const statusReducer = (state, action) => { | |
if (alllowedStatus.includes(action.state)) { | |
return { | |
...state, | |
...action, | |
} | |
} | |
console.warn(`Invalid state ${action.state} passed to useStatus.`) | |
return state | |
} | |
const useStatus = (initialStatus: AllowedStatus = 'idle') => { | |
const [state, dispatch] = useReducer<Status, Status>( | |
statusReducer, | |
initialState | |
) | |
return [state, dispatch] | |
} | |
export default useStatus |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment