0
0
React Nativemobile~5 mins

AbortController for cancellation in React Native

Choose your learning style9 modes available
Introduction

AbortController helps you stop a task like a network request if you don't need it anymore. This saves time and device power.

When a user leaves a screen before a data fetch finishes.
When you want to cancel a slow network request to try a faster one.
When you want to stop a fetch if the app goes offline.
When you want to avoid updating the UI with old data after navigation.
Syntax
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.

Examples
Basic example: start fetch and cancel it later.
React Native
const controller = new AbortController();
fetch('https://api.example.com/data', { signal: controller.signal });
// Later
controller.abort();
Cancel fetch automatically after 3 seconds.
React Native
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);
Sample App

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.

React Native
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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.