66 lines
1.1 KiB
TypeScript
66 lines
1.1 KiB
TypeScript
import { useState } from 'preact/hooks'
|
|
import isLoading from '../utils/is_loading.ts'
|
|
|
|
interface State<E extends Error> {
|
|
error: E | null
|
|
pending: boolean
|
|
success: boolean
|
|
response: any
|
|
}
|
|
|
|
const useRequestState = <E extends Error>() => {
|
|
const initialState = {
|
|
error: null,
|
|
pending: false,
|
|
success: false,
|
|
response: null,
|
|
}
|
|
|
|
const [state, setState] = useState<State<E>>(initialState)
|
|
|
|
const actions = {
|
|
reset() {
|
|
isLoading(false)
|
|
|
|
setState(initialState)
|
|
},
|
|
|
|
error(error: E) {
|
|
isLoading(false)
|
|
|
|
setState({
|
|
pending: false,
|
|
success: false,
|
|
error,
|
|
response: null,
|
|
})
|
|
},
|
|
|
|
pending() {
|
|
isLoading(true)
|
|
|
|
setState({
|
|
pending: true,
|
|
success: false,
|
|
error: null,
|
|
response: null,
|
|
})
|
|
},
|
|
|
|
success(response = null) {
|
|
isLoading(false)
|
|
|
|
setState({
|
|
pending: false,
|
|
success: true,
|
|
error: null,
|
|
response,
|
|
})
|
|
},
|
|
}
|
|
|
|
return [state, actions] as [State<E>, typeof actions]
|
|
}
|
|
|
|
export default useRequestState
|