forked from ohcnetwork/care_fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adds support for
useMutation
hook (ohcnetwork#8891)
- Loading branch information
1 parent
c51b88b
commit 5ce520f
Showing
3 changed files
with
64 additions
and
35 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import request from "@/Utils/request/request"; | ||
import { | ||
MutationRoute, | ||
RequestOptions, | ||
RequestResult, | ||
} from "@/Utils/request/types"; | ||
import { mergeRequestOptions } from "@/Utils/request/utils"; | ||
import React from "react"; | ||
|
||
export default function useMutation<TData, TBody>( | ||
route: MutationRoute<TData, TBody>, | ||
options: RequestOptions<TData>, | ||
) { | ||
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>) => { | ||
controllerRef.current?.abort(); | ||
|
||
const controller = new AbortController(); | ||
controllerRef.current = controller; | ||
|
||
const resolvedOptions = | ||
options && overrides | ||
? mergeRequestOptions(options, overrides) | ||
: (overrides ?? options); | ||
|
||
setIsProcessing(true); | ||
const response = await request(route, { ...resolvedOptions, controller }); | ||
setResponse(response); | ||
setIsProcessing(false); | ||
return response; | ||
}, | ||
[route, JSON.stringify(options)], | ||
); | ||
|
||
return { ...response, isProcessing, mutate: runQuery }; | ||
} |
This file contains 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