Skip to content

Instantly share code, notes, and snippets.

@akramsaouri
Last active September 8, 2020 15:25
Show Gist options
  • Save akramsaouri/7688bb7a0a9b11834925004f0bd6a28a to your computer and use it in GitHub Desktop.
Save akramsaouri/7688bb7a0a9b11834925004f0bd6a28a to your computer and use it in GitHub Desktop.
⚛️ No more isLoading or hasErrored
// @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