Cancel a fetch request in react-native

I've written quite a bit actually about this subject. You can also find the first issue about the OLD lack of AbortController in React Native opened by me here

The support landed in RN 0.60.0 and you can find on my blog an article about this and another one that will give you a simple code to get you started on making abortable requests (and more) in React Native too. It also implements a little polyfill for non supporting envs (RN < 0.60 for example).


You can Actually achieve this by installing this polyfill abortcontroller-polyfill Here is a quick example of cancelling requests:

import React from 'react';
import { Button, View, Text } from 'react-native';
import 'abortcontroller-polyfill';

export default class HomeScreen extends React.Component {
  state = { todos: [] };

  controller = new AbortController();

  doStuff = () => {
    fetch('https://jsonplaceholder.typicode.com/todos',{
      signal: this.controller.signal
    })
    .then(res => res.json())
    .then(todos => {
      alert('done');
      this.setState({ todos })
    })
    .catch(e => alert(e.message));
    alert('calling cancel');
    this.controller.abort()
  }


  render(){
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button title="Do stuff" onPress={() => { this.doStuff(); }} /> 
      </View>
    )
  }
}

So basically in this example, once you click the 'doStuff' button, the request is immediately cancelled and you never get the 'done' alert. To be sure, it works, try and comment out these lines and click the button again:

alert('calling cancel');
this.controller.abort()

This time you will get the 'done' alert.

This is a simple example of hoe you can cancel a request using fetch in react native, feel free to adopt this to your own use case.

Here is a link to a demo on snackexpo https://snack.expo.io/@mazinoukah/fetch-cancel-request

hope it helps :)


You don't need any polyfill anymore for abort a request in React Native 0.60 changelog

Here is a quick example from the doc of react-native:

/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
*/

'use strict';

const React = require('react');
const {Alert, Button, View} = require('react-native');

class XHRExampleAbortController extends React.Component<{}, {}> {
  _timeout: any;

  _submit(abortDelay) {
    clearTimeout(this._timeout);
    // eslint-disable-next-line no-undef
    const abortController = new AbortController();
    fetch('https://facebook.github.io/react-native/', {
      signal: abortController.signal,
    })
      .then(res => res.text())
      .then(res => Alert.alert(res))
      .catch(err => Alert.alert(err.message));
    this._timeout = setTimeout(() => {
          abortController.abort();
    }, abortDelay);
  }

  componentWillUnmount() {
    clearTimeout(this._timeout);
  }

  render() {
    return (
      <View>
        <Button
          title="Abort before response"
          onPress={() => {
            this._submit(0);
          }}
        />
        <Button
          title="Abort after response"
          onPress={() => {
            this._submit(5000);
          }}
        />
      </View>
    );
  }
}

module.exports = XHRExampleAbortController;