From b42d8a51a9b810a683e184ffc800291475663a6e Mon Sep 17 00:00:00 2001 From: giancarlo Date: Mon, 22 Apr 2024 12:04:12 +0800 Subject: [PATCH] Refactor API fetch using React Query The code has been updated to use the React Query library for API fetch operations in README.md. The mutation function has been abstracted using 'useMutation' from '@tanstack/react-query', replacing the traditional fetch operation. This leads to cleaner and more reusable code. --- README.md | 53 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0be353f43..b1f983ed8 100644 --- a/README.md +++ b/README.md @@ -507,20 +507,63 @@ function Component() { email: string; password: string; }) => { - const response = await fetch('/api/my-api-route', { + const response = await fetch('/my-api-route', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-csrf-token': csrfToken, + 'x-captcha-token': captchaToken, }, - body: JSON.stringify({ - ...params, - captchaToken, - }), + body: JSON.stringify(params), }); // ... your code here }; + + // ... your code here +} +``` + +You can improve the above using React Query: + +```tsx +import { useMutation } from '@tanstack/react-query'; +import { useCaptchaToken } from '@kit/auth/captcha/client'; + +function Component() { + const captchaToken = useCaptchaToken(); + const mutation = useMutateData(); + + const onSubmit = async (params: { + email: string; + password: string; + }) => { + await mutation.mutateAsync(params); + }; + + // ... your code here +} + +function useMutateData() { + return useMutation({ + mutationKey: 'my-mutation', + mutationFn: async (params: { email: string; password: string }) => { + const response = await fetch('/my-api-route', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-captcha-token': captchaToken, + }, + body: JSON.stringify(params), + }); + + if (!response.ok) { + throw new Error('An error occurred'); + } + + return response.json(); + }, + }); } ```