Fixed useSend loading flow on abort

Made data null on error
Made it remain in loading state on refetch and remount abortion
This commit is contained in:
2023-08-12 01:32:02 +03:00
parent 3bf00cea6a
commit b12f19ac51
5 changed files with 60 additions and 29 deletions

View File

@ -20,7 +20,7 @@ type UseFetchLoading = {
} & UseFetchShared
type UseFetchErrored = {
data: undefined,
data: null,
loading: false,
error: string,
} & UseFetchShared
@ -32,8 +32,7 @@ const gotError = <T>(res: UseFetchReturn<T>): res is UseFetchErrored => (
)
function fallbackError<T>(res: UseFetchSucced<T> | UseFetchErrored): T | string
function fallbackError<T>(res: UseFetchReturn<T>): T | string | undefined
function fallbackError<T>(res: UseFetchReturn<T>): T | string | undefined {
function fallbackError<T>(res: UseFetchReturn<T>): T | string | null | undefined {
return (
gotError(res) ? res.error : res.data
)
@ -62,7 +61,6 @@ function useFetch<R, T extends NonNullable<unknown>>(
needAuth,
guardResponse,
processResponse,
true,
params,
)
@ -70,10 +68,14 @@ function useFetch<R, T extends NonNullable<unknown>>(
setFetchLoading(true)
doSend().then(
data => {
if (data !== undefined) {
if (data !== undefined && data !== null) {
setData(data)
console.log('Got data', data)
}
if (data !== undefined) {
setFetchLoading(false)
}
setFetchLoading(false)
}
).catch( // must never occur
err => import.meta.env.DEV && console.error('Failed to do fetch request', err)
@ -93,7 +95,7 @@ function useFetch<R, T extends NonNullable<unknown>>(
if (error !== null) {
return {
data: undefined,
data: null,
loading: fetchLoading,
error,
refetch,