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.
This commit is contained in:
53
README.md
53
README.md
@@ -507,20 +507,63 @@ function Component() {
|
|||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
}) => {
|
}) => {
|
||||||
const response = await fetch('/api/my-api-route', {
|
const response = await fetch('/my-api-route', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'x-csrf-token': csrfToken,
|
'x-csrf-token': csrfToken,
|
||||||
|
'x-captcha-token': captchaToken,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(params),
|
||||||
...params,
|
|
||||||
captchaToken,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ... your code here
|
// ... 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();
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user