I have MERN stack application and I want to cancel an API request when the back button is pressed.
useEffect(()=>{
const controller = new AbortController();
const fetchSingleUser = async () =>{
const response = await axios.get(`/users/singleUser/${path}`, {
signal: controller.signal})
setUser(response.data)
}
fetchSingleUser()
return function cancel() {
console.log('abort')
controller.abort()
}
}, [path])
When I opened this page and hit the browser back button to go back to another page, I checked network and saw that the API request was running on the background until it completes. It should have canceled the request.