Last active
January 3, 2025 21:04
-
-
Save nmoinvaz/2cc2307b241bad2835dcc77645eede3b to your computer and use it in GitHub Desktop.
useQuery with Enhanced Error Handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useCallback, useEffect, useMemo, useState} from "react"; | |
import {useQuery} from "react-query"; | |
// Provide ability to reset the error | |
const useEnhancedQuery = (queryKey, queryFn, options) => { | |
const {error: queryError, refetch: queryRefetch, status, ...queryResult} = | |
useQuery(queryKey, queryFn, options); | |
const [error, setError] = useState(queryError); | |
useEffect(() => { | |
if (queryError) { | |
setError(queryError); | |
} else if (status === "success") { | |
setError(null); | |
} | |
}, [queryError, status]); | |
const refetchWithReset = useCallback(() => { | |
// Reset error before refetch. | |
setError(null); | |
return queryRefetch(); | |
}, [queryRefetch]); | |
const resetError = useCallback(() => { | |
setError(null); | |
}, []); | |
return useMemo(() => ({ | |
...queryResult, | |
error, | |
isError: !!error, | |
status, | |
refetch: refetchWithReset, | |
resetError | |
}), [queryResult, error, status, refetchWithReset, resetError]); | |
}; | |
export default useEnhancedQuery; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: