'Cancelling Axios request in React when using React Router Switch
I'm a newbie building an App that utilizes React Router to switch between 3 different components that each utilize Axios to fetch data from an API. I am trying to cancel the API request whenever a navlink is clicked to prevent the "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function" error in console. First I tried using AbortController in the App.js where the links are by adding click events that utilized controller.abort();. When that didn't work I tried directly where Axios was being called(seen in DisplayFish.js in my code sandbox example below) and still no luck. I have a simplified version of the main page with links and 1 of the components to show my code here https://codesandbox.io/s/white-voice-s8moo?file=/src/App.js Appreciate any help!
Solution 1:[1]
You can use cancel axios request using axios.CancelToken.
const cancelTokenSource = axios.CancelToken.source();
axios.get('/user/12345', {
cancelToken: cancelTokenSource.token
});
// Cancel request
cancelTokenSource.cancel();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | First Arachne |