mirror of
https://github.com/muerwre/muerwre.github.io.git
synced 2025-04-25 10:56:40 +07:00
added whole content
This commit is contained in:
parent
07a306a6f4
commit
dd104eed49
70 changed files with 5962 additions and 19 deletions
32
content/Frontend/React/Axios with AbortController.md
Normal file
32
content/Frontend/React/Axios with AbortController.md
Normal file
|
@ -0,0 +1,32 @@
|
|||
If you need to cancel some request, use [axios with AbortController](https://axios-http.com/docs/cancellation). Previously axios used cancellation token, but now it's deprecated.
|
||||
|
||||
`AbortController` can be used with a multiple requests to cancel them at once.
|
||||
|
||||
```typescript
|
||||
import { useCallback, useRef } from "react";
|
||||
import axios from 'axios';
|
||||
|
||||
const client = axios.create();
|
||||
|
||||
export const useGetUsers = () => {
|
||||
const controller = useRef(new AbortController());
|
||||
|
||||
const get = useCallback(async () => {
|
||||
const result = await client.get("/", {
|
||||
// params and props here
|
||||
signal: controller.current.signal,
|
||||
});
|
||||
|
||||
return result.data;
|
||||
}, []);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
controller.current.abort();
|
||||
|
||||
// controller should be rewritten or all requests will fail
|
||||
controller.current = new AbortController();
|
||||
}, [controller]);
|
||||
|
||||
return { get, cancel };
|
||||
};
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue