AbortController helps you stop a task like a network request if you don't need it anymore. This saves time and device power.
AbortController for cancellation in React Native
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', error);
}
});
// To cancel the fetch
controller.abort();The AbortController creates a signal to tell fetch when to stop.
Calling controller.abort() cancels the fetch and triggers an error with name AbortError.
const controller = new AbortController();
fetch('https://api.example.com/data', { signal: controller.signal });
// Later
controller.abort();const controller = new AbortController(); fetch('https://api.example.com/data', { signal: controller.signal }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => { if (err.name === 'AbortError') { console.log('Request was cancelled'); } }); // Cancel after 3 seconds setTimeout(() => controller.abort(), 3000);
This React Native component fetches data when you press "Start Fetch". You can cancel the fetch anytime by pressing "Cancel Fetch". It shows loading, data, or cancellation message.
import React, { useEffect, useState, useRef } from 'react'; import { View, Text, Button } from 'react-native'; export default function FetchWithAbort() { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const controllerRef = useRef(new AbortController()); const startFetch = () => { setLoading(true); setError(null); setData(null); controllerRef.current.abort(); controllerRef.current = new AbortController(); fetch('https://jsonplaceholder.typicode.com/todos/1', { signal: controllerRef.current.signal }) .then(res => res.json()) .then(json => { setData(json); setLoading(false); }) .catch(err => { if (err.name === 'AbortError') { setError('Fetch cancelled'); } else { setError('Fetch error'); } setLoading(false); }); }; const cancelFetch = () => { controllerRef.current.abort(); }; useEffect(() => { return () => { controllerRef.current.abort(); }; }, []); return ( <View style={{ padding: 20 }}> <Button title="Start Fetch" onPress={startFetch} disabled={loading} /> <Button title="Cancel Fetch" onPress={cancelFetch} disabled={!loading} /> {loading && <Text>Loading...</Text>} {data && <Text>Title: {data.title}</Text>} {error && <Text>{error}</Text>} </View> ); }
Always handle the AbortError to avoid confusing error messages.
AbortController works only with APIs that support the signal option, like fetch.
Remember to abort fetches in useEffect cleanup to avoid memory leaks.
AbortController lets you stop fetch requests early.
Use it to save resources and improve app responsiveness.
Always handle cancellation errors to keep your app smooth.
Practice
AbortController in React Native fetch requests?Solution
Step 1: Understand what AbortController does
AbortController provides a way to stop a fetch request that is still running.Step 2: Compare options with AbortController's purpose
Only To cancel an ongoing fetch request before it completes describes stopping or canceling a fetch request early.Final Answer:
To cancel an ongoing fetch request before it completes -> Option AQuick Check:
AbortController cancels fetch = B [OK]
- Thinking it speeds up fetch automatically
- Confusing cancellation with retry
- Assuming it caches data
Solution
Step 1: Check how to instantiate AbortController
It must be created with the new keyword:new AbortController().Step 2: Verify how to pass the signal to fetch
The fetch option key issignaland its value iscontroller.signal.Final Answer:
const controller = new AbortController(); fetch(url, { signal: controller.signal }); -> Option DQuick Check:
Use new and pass signal property = C [OK]
- Omitting the new keyword
- Passing controller instead of controller.signal
- Using wrong option keys like abort or cancelToken
const controller = new AbortController();
fetch('https://example.com/data', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log('Data:', data))
.catch(error => console.log('Error:', error.name));
controller.abort();
What will be logged to the console?Solution
Step 1: Understand what controller.abort() does
Calling abort() cancels the fetch request, triggering an error with name 'AbortError'.Step 2: Check the catch block behavior
The catch block logs the error name, so it will log 'AbortError'.Final Answer:
Error: AbortError -> Option AQuick Check:
Abort triggers AbortError catch = A [OK]
- Expecting data to log after abort
- Confusing AbortError with TypeError
- Thinking nothing logs on abort
const controller = new AbortController();
fetch('https://api.example.com', { signal: controller.signal });
// Some code
controller.abort();
What is the most likely reason the fetch is not canceled?Solution
Step 1: Understand timing of abort()
If abort() is called after fetch completes, it has no effect.Step 2: Check other options
Signal is assigned correctly, and abort() is called after fetch starts, so those are not issues.Final Answer:
The fetch request already completed before abort() was called -> Option CQuick Check:
Abort after fetch finishes does nothing = A [OK]
- Ignoring fetch completion timing
- Assuming abort always cancels
- Not handling errors but expecting cancel
Solution
Step 1: Setup AbortController and timeout before fetch
Create controller, then set a timeout to call abort after 3 seconds.Step 2: Pass controller.signal to fetch and handle errors
Pass signal option to fetch and catch abort errors to avoid unhandled exceptions.Final Answer:
const controller = new AbortController(); setTimeout(() => controller.abort(), 3000); fetch(url, { signal: controller.signal }) .catch(e => console.log(e.name)); -> Option BQuick Check:
Timeout abort + signal + catch = D [OK]
- Calling abort without passing signal to fetch
- Not catching abort errors
- Calling abort after fetch without signal
Ready to prove it?
Pass the test and this pattern moves unknown
