Fixed ann removal

This commit is contained in:
2023-07-29 18:43:44 +03:00
parent e214ea53e7
commit cf81e3d817
6 changed files with 53 additions and 27 deletions

View File

@ -1,27 +1,26 @@
import { useEffect, useState } from 'react'
import { SetState } from '../utils/types'
import useSend from './useSend'
type UseFetchShared<T> = {
type UseFetchShared = {
loading: boolean,
abort?: () => void,
setData: SetState<T | undefined>
refetch: () => void,
}
type UseFetchSucced<T> = {
error: null,
data: T,
} & UseFetchShared<T>
} & UseFetchShared
type UseFetchErrored<T> = {
type UseFetchErrored = {
error: string,
data: undefined
} & UseFetchShared<T>
} & UseFetchShared
type UseFetchReturn<T> = UseFetchSucced<T> | UseFetchErrored<T>
type UseFetchReturn<T> = UseFetchSucced<T> | UseFetchErrored
const gotError = <T>(res: UseFetchReturn<T>): res is UseFetchErrored<T> => (
const gotError = <T>(res: UseFetchReturn<T>): res is UseFetchErrored => (
typeof res.error === 'string'
)
@ -40,15 +39,25 @@ function useFetch<R, T extends NonNullable<unknown>>(
): UseFetchReturn<T> {
const [data, setData] = useState(initialData)
const { doSend, loading, error } = useSend(url, method, needAuth, guardResponse, processResponse, true, params)
const { doSend, loading, error } = useSend(
url,
method,
needAuth,
guardResponse,
processResponse,
true,
params
)
useEffect(() => {
function refetch() {
doSend().then(
data => { if (data !== undefined) setData(data) }
).catch( // must never occur
err => import.meta.env.DEV && console.error('Failed to do fetch request', err)
)
}, [doSend])
}
useEffect(refetch, [doSend])
return {
...(
@ -57,7 +66,7 @@ function useFetch<R, T extends NonNullable<unknown>>(
}) : ({ data: undefined, error })
),
loading,
setData
refetch
}
}