From 532945766d2b76bd64dc4ce7ced9aceedece313d Mon Sep 17 00:00:00 2001 From: Rithvik Nishad Date: Wed, 27 Nov 2024 21:12:10 +0530 Subject: [PATCH] Fix loading state management in useQuery when requests are aborted (#9222) --- src/Utils/request/request.ts | 3 +++ src/Utils/request/useMutation.ts | 10 ++++++---- src/Utils/request/useQuery.ts | 6 ++++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Utils/request/request.ts b/src/Utils/request/request.ts index d036ad49750..847b7c9ba60 100644 --- a/src/Utils/request/request.ts +++ b/src/Utils/request/request.ts @@ -70,6 +70,9 @@ export default async function request( return result; } catch (error: any) { result = { error, res: undefined, data: undefined }; + if (error.name === "AbortError") { + return result; + } } } diff --git a/src/Utils/request/useMutation.ts b/src/Utils/request/useMutation.ts index fbc6edc3940..7c368f5e45d 100644 --- a/src/Utils/request/useMutation.ts +++ b/src/Utils/request/useMutation.ts @@ -10,7 +10,7 @@ import { mergeRequestOptions } from "@/Utils/request/utils"; export default function useMutation( route: MutationRoute, - options: RequestOptions, + options: RequestOptions, ) { const [response, setResponse] = React.useState>(); const [isProcessing, setIsProcessing] = React.useState(false); @@ -18,7 +18,7 @@ export default function useMutation( const controllerRef = React.useRef(); const runQuery = React.useCallback( - async (overrides?: RequestOptions) => { + async (overrides?: RequestOptions) => { controllerRef.current?.abort(); const controller = new AbortController(); @@ -31,8 +31,10 @@ export default function useMutation( setIsProcessing(true); const response = await request(route, { ...resolvedOptions, controller }); - setResponse(response); - setIsProcessing(false); + if (response.error?.name !== "AbortError") { + setResponse(response); + setIsProcessing(false); + } return response; }, [route, JSON.stringify(options)], diff --git a/src/Utils/request/useQuery.ts b/src/Utils/request/useQuery.ts index 109ff0bb2f1..5f4c10a289e 100644 --- a/src/Utils/request/useQuery.ts +++ b/src/Utils/request/useQuery.ts @@ -37,8 +37,10 @@ export default function useQuery( setLoading(true); const response = await request(route, { ...resolvedOptions, controller }); - setResponse(response); - setLoading(false); + if (response.error?.name !== "AbortError") { + setResponse(response); + setLoading(false); + } return response; }, [route, JSON.stringify(options)],