Fixed fetch loading ending before result saving

This commit is contained in:
Dmitriy Shishkov 2023-08-09 17:55:54 +03:00
parent fa98b392a8
commit f8235ca7f4
Signed by: dm1sh
GPG Key ID: 027994B0AA357688

View File

@ -1,4 +1,4 @@
import { useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import useSend from './useSend' import useSend from './useSend'
@ -54,7 +54,9 @@ function useFetch<R, T extends NonNullable<unknown>>(
): UseFetchReturn<T> { ): UseFetchReturn<T> {
const [data, setData] = useState(initialData) const [data, setData] = useState(initialData)
const { doSend, loading, error } = useSend( const [fetchLoading, setFetchLoading] = useState(true)
const { doSend, error } = useSend(
url, url,
method, method,
needAuth, needAuth,
@ -64,20 +66,26 @@ function useFetch<R, T extends NonNullable<unknown>>(
params, params,
) )
function refetch() { const refetch = useCallback(() => {
setFetchLoading(true)
doSend().then( doSend().then(
data => { if (data !== undefined) setData(data) } data => {
if (data !== undefined) {
setData(data)
}
setFetchLoading(false)
}
).catch( // must never occur ).catch( // must never occur
err => import.meta.env.DEV && console.error('Failed to do fetch request', err) err => import.meta.env.DEV && console.error('Failed to do fetch request', err)
) )
} }, [doSend])
useEffect(refetch, [doSend]) useEffect(refetch, [refetch])
if (loading === true) { if (fetchLoading === true) {
return { return {
data: undefined, data: undefined,
loading, loading: fetchLoading,
error: null, error: null,
refetch, refetch,
} }
@ -86,7 +94,7 @@ function useFetch<R, T extends NonNullable<unknown>>(
if (error !== null) { if (error !== null) {
return { return {
data: undefined, data: undefined,
loading, loading: fetchLoading,
error, error,
refetch, refetch,
} }
@ -94,7 +102,7 @@ function useFetch<R, T extends NonNullable<unknown>>(
return { return {
data: data!, data: data!,
loading, loading: fetchLoading,
error, error,
refetch, refetch,
} }