react-use-cancel-token
v1.0.3
Published
A handy react hook to cancel axios requests
Downloads
2,895
Maintainers
Readme
useCancelToken
A handy react hook to cancel axios requests
Demo
Install
npm install --save react-use-cancel-token
Usage
useAbortController
import * as React from 'react';
import axios from 'axios';
import useAbortController from 'react-use-cancel-token';
const Example = () => {
const { newAbortSignal, cancelPreviousRequest, isCancel } = useAbortController();
const handleClick = async () => {
cancelPreviousRequest();
try {
const response = await axios.get('request_url', { signal: newAbortSignal() });
if (response.status === 200) {
// handle success
}
} catch (err) {
if (isCancel(err)) return;
console.error(err);
}
};
return <button onClick={handleClick}>send request</button>;
};
Outputs
| Property | Type | Description |
| ----------------------- | ------------------- | --------------------------------------------------------------------- |
| controller
| MutableObjectRef
| Reference to the AbortController instance |
| newAbortSignal
| () => AbortSignal
| Generate the abort signal sent in the Axios request |
| cancelPreviousRequest
| () => void
| Cancel any previous Axios request |
| isCancel
| () => boolean
| Check if the error returned in Axios response is an abort error |
useCancelToken (deprecated)
import * as React from 'react';
import axios from 'axios';
import { useCancelToken } from 'react-use-cancel-token';
const Example = () => {
const { newCancelToken, cancelPreviousRequest, isCancel } = useCancelToken();
const handleClick = async () => {
cancelPreviousRequest();
try {
const response = await axios.get('request_url', { cancelToken: newCancelToken() });
if (response.status === 200) {
// handle success
}
} catch (err) {
if (isCancel(err)) return;
console.error(err);
}
};
return <button onClick={handleClick}>send request</button>;
};
Outputs
| Property | Type | Description |
| ----------------------- | ------------------- | --------------------------------------------------------------------- |
| source
| MutableObjectRef
| Reference to Axios cancel token source |
| newCancelToken
| () => CancelToken
| Generate the cancel token sent in the Axios request |
| cancelPreviousRequest
| () => void
| Cancel any previous Axios request |
| isCancel
| () => boolean
| Check if the error returned in Axios response is a cancel token error |
License
MIT © AXeL-dev