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'
@ -54,7 +54,9 @@ function useFetch<R, T extends NonNullable<unknown>>(
): UseFetchReturn<T> {
const [data, setData] = useState(initialData)
const { doSend, loading, error } = useSend(
const [fetchLoading, setFetchLoading] = useState(true)
const { doSend, error } = useSend(
url,
method,
needAuth,
@ -64,20 +66,26 @@ function useFetch<R, T extends NonNullable<unknown>>(
params,
)
function refetch() {
const refetch = useCallback(() => {
setFetchLoading(true)
doSend().then(
data => { if (data !== undefined) setData(data) }
data => {
if (data !== undefined) {
setData(data)
}
setFetchLoading(false)
}
).catch( // must never occur
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 {
data: undefined,
loading,
loading: fetchLoading,
error: null,
refetch,
}
@ -86,7 +94,7 @@ function useFetch<R, T extends NonNullable<unknown>>(
if (error !== null) {
return {
data: undefined,
loading,
loading: fetchLoading,
error,
refetch,
}
@ -94,7 +102,7 @@ function useFetch<R, T extends NonNullable<unknown>>(
return {
data: data!,
loading,
loading: fetchLoading,
error,
refetch,
}