Skip to content

Commit

Permalink
Fix loading state management in useQuery when requests are aborted (o…
Browse files Browse the repository at this point in the history
  • Loading branch information
rithviknishad authored Nov 27, 2024
1 parent 3e19607 commit 5329457
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
3 changes: 3 additions & 0 deletions src/Utils/request/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ export default async function request<TData, TBody>(
return result;
} catch (error: any) {
result = { error, res: undefined, data: undefined };
if (error.name === "AbortError") {
return result;
}
}
}

Expand Down
10 changes: 6 additions & 4 deletions src/Utils/request/useMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ import { mergeRequestOptions } from "@/Utils/request/utils";

export default function useMutation<TData, TBody>(
route: MutationRoute<TData, TBody>,
options: RequestOptions<TData>,
options: RequestOptions<TData, TBody>,
) {
const [response, setResponse] = React.useState<RequestResult<TData>>();
const [isProcessing, setIsProcessing] = React.useState(false);

const controllerRef = React.useRef<AbortController>();

const runQuery = React.useCallback(
async (overrides?: RequestOptions<TData>) => {
async (overrides?: RequestOptions<TData, TBody>) => {
controllerRef.current?.abort();

const controller = new AbortController();
Expand All @@ -31,8 +31,10 @@ export default function useMutation<TData, TBody>(

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)],
Expand Down
6 changes: 4 additions & 2 deletions src/Utils/request/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@ export default function useQuery<TData>(

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)],
Expand Down

0 comments on commit 5329457

Please sign in to comment.