Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel a fetch request in react-native

Is there any way to abort a fetch request on react-native app ?

class MyComponent extends React.Component {
  state = { data: null };

  componentDidMount = () =>
    fetch('http://www.example.com')
      .then(data => this.setState({ data }))
      .catch(error => {
        throw error; 
      });

  cancelRequest = () => {
   //???
  };

  render = () => <div>{this.state.data ? this.state.data : 'loading'}</div>;
}

i tried the abort function from AbortController class but it's not working !!

...
abortController = new window.AbortController();

cancelRequest =  () => this.abortController.abort();

componentDidMount = () =>
        fetch('http://www.example.com', { signal: this.abortController.signal })
          ....

Any help please !

like image 485
AHméd Net Avatar asked May 13 '19 23:05

AHméd Net


People also ask

Can fetch request be canceled?

To be able to cancel fetch , pass the signal property of an AbortController as a fetch option: let controller = new AbortController(); fetch(url, { signal: controller. signal }); The fetch method knows how to work with AbortController .

How do I cancel API request?

Cancel Fetch request If you want to cancel a Fetch request, you need to use the AbortController API. You can use the constructor to create a new AbortController object. It has a read-only property AbortController.

How do you cancel async task in React?

Also, in order to cancel an active fetch request, you need to use an AbortController instance. Try the demo. let controller = new AbortController() creates an instance of the abort controller. Then await fetch(..., { signal: controller.


2 Answers

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).

like image 199
Giacomo Cerquone Avatar answered Oct 10 '22 19:10

Giacomo Cerquone


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;
like image 43
P-A Bouly Avatar answered Oct 10 '22 21:10

P-A Bouly