User navigates away but old fetch requests keep running in background. Cancel them properly with AbortController.
Setup:
const controller = new AbortController();
fetch('/api/data', {
signal: controller.signal
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request cancelled');
}
});
// Cancel when user leaves page
window.addEventListener('beforeunload', () => {
controller.abort();
});
React Example:
useEffect(() => {
const controller = new AbortController();
fetch('/api/users', { signal: controller.signal })
.then(r => r.json())
.then(setUsers);
return () => controller.abort(); // Cleanup
}, []);
Prevents memory leaks and unnecessary network traffic!
