I’m trying to cancel axios request by token in useEffect:
// http-request.js
export const cancelelationSource = axios.CancelToken.source();
export const get = endpoint => {
return axios.get(endpoint, {
headers: { ...headers },
timeout: 20000,
cancelToken: cancelelationSource.token
})
.then(response => response.data)
.catch(e => {
console.log(e);
});
}
then in component:
import { get, cancelelationSource } from './http-request';
const About = () => {
useEffect(() => {
get('http://localhost:3001/test2').then(data => console.log(data))
}, []);
return (
<h1>About</h1>
)
}
const App = () => {
useEffect(() => {
get('http://localhost:3001/test').then(data => console.log(data))
return () => cancelelationSource.cancel();
}, []);
return (
<div>
<Link to="/about">About</Link>
</div>
)
}
render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>,
document.getElementById('root')
);
request cancelation works well when I click on the About link. but second API fetch doesn’t work in component <About />
I think axios cancels all requests… I want cancel previous requests but new request should be able to fetch data after change pages or redirect!