Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AbortController is missing #18115

Closed
giacomocerquone opened this Issue Feb 27, 2018 · 23 comments

Comments

Projects
None yet
@giacomocerquone
Copy link

giacomocerquone commented Feb 27, 2018

Is this a bug report?

Yes. AbortController is a new spec (you can find info here: https://developers.google.com/web/updates/2017/09/abortable-fetch)

Have you read the Contributing Guidelines?

Yes

Environment

Environment:
  OS: Linux 4.13
  Node: 8.9.4
  Yarn: 1.3.2
  npm: 5.6.0
  Watchman: Not Found
  Xcode: N/A
  Android Studio: Not Found

Packages: (wanted => installed)
  react: ^16.0.0 => 16.2.0
  react-native: ^0.53.0 => 0.53.0

Steps to Reproduce

  1. Istantiate an AbortController
  2. Write a fetch request passing the signal
  3. Try to abort the fetch request

Expected Behavior

The requested behaviour is to abort the fetch request.

Actual Behavior

Nothing happens

Reproducible Demo

Something like this:

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 5000);

fetch(url, { signal }).then(response => {
  return response.text();
}).then(text => {
  console.log(text);
});

My question is a technical one: is the react native core that needs to be updated in order to support this? Or is it something that babel can patch with a new version?

@hyochan

This comment has been minimized.

Copy link
Contributor

hyochan commented Feb 27, 2018

Having same issue. This should be in react-native too.

@chirag04

This comment has been minimized.

Copy link
Collaborator

chirag04 commented Feb 27, 2018

might be worth waiting for github/fetch#572 to merge.

@giacomocerquone

This comment has been minimized.

Copy link
Author

giacomocerquone commented Feb 27, 2018

Very good, at least I should be able to use this polyfill right now in react native right?

@chirag04

This comment has been minimized.

Copy link
Collaborator

chirag04 commented Feb 27, 2018

I haven’t used it but should be able to use it. Might be worth posting here what you find out

@giacomocerquone

This comment has been minimized.

Copy link
Author

giacomocerquone commented Feb 27, 2018

Great, it works!
I'm not on a create react app, but I've just followed the instruction for it (I'm actually on a react-native project not even on a create react native app

So installed the module, imported it like this:

import 'abortcontroller-polyfill';

and then used it like this:

const AbortController = window.AbortController;
const controller = new AbortController()
const signal = controller.signal

I'd not close the issue, because we're still waiting for the official spec.
Thank you @chirag04 for linking me the right resource ☺️

@sibelius

This comment has been minimized.

Copy link

sibelius commented Mar 25, 2018

@giacomocerquone the polyfill is working on react-native (#18115 (comment))

do u have an example of it?

@giacomocerquone

This comment has been minimized.

Copy link
Author

giacomocerquone commented Mar 25, 2018

Just doing what I wrote in the previous comment should be fine. All the code then would be equals to the one used in the browsers like the piece showed on mozilla doc: https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort

I've actually a production app where I'm using this. I can't share directly the code of course, but I can re-arrange an example if it is strictly needed :)

@sibelius

This comment has been minimized.

Copy link

sibelius commented Mar 25, 2018

it works, but won't really cancel the request, it will just throw an exception

tks

@giacomocerquone

This comment has been minimized.

Copy link
Author

giacomocerquone commented Mar 25, 2018

Basically it just rejects the promise.
It's true that it won't cancel the request (we should also specify precisely what we mean when we write 'cancel'), but as far as I'm concerned, my interest was to not let the request hanging and to 'close the door' to all the responses that would have come after the abort call.

@stale

This comment has been minimized.

Copy link

stale bot commented Jun 23, 2018

Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. You may also label this issue as "For Discussion" or "Good first issue" and I will leave it open. Thank you for your contributions.

@stale stale bot added the Stale label Jun 23, 2018

@mrjackyliang

This comment has been minimized.

Copy link

mrjackyliang commented Jun 24, 2018

I just tried it today with the polyfills, and it doesn’t work.

@stale stale bot removed the Stale label Jun 24, 2018

@JoseVf

This comment has been minimized.

Copy link

JoseVf commented Aug 8, 2018

Is there any update about this?


@giacomocerquone It would be nice if you can provide an example to understand better how it works 😄
@AugustGSP

This comment has been minimized.

Copy link

AugustGSP commented Aug 28, 2018

Any update on this?

AbortController + signal imports and fires, but the fetch is not interrupted. I tried @giacomocerquone 's resolution, but that didn't abort the fetch either. Is there another polyfill i'm missing?

function api(endpoint, method, body, contentType = 'application/json') {
	
	const controller = new AbortController()
	const signal = controller.signal
	setTimeout(() => controller.abort(), 500)

	let data = {
		signal,
		method: method,
		headers: {
			'Content-Type': contentType
		} 
	}

	if (body) {
		data['body'] = JSON.stringify(body)
	}

	return fetch(`${API_URI}/${endpoint}`, data)
	.then(response => {
		if (!response.ok) {
			throw Error(response.statusText)
		}

		return response.json()
	})
	.then(response => {
		return response.data
	})
	.catch(error => {
		console.log('API request failed:', error.message)

		return false
	})
}
@TimurAsayonok

This comment has been minimized.

Copy link

TimurAsayonok commented Aug 29, 2018

Same problem.

Try to cancel fetch after timeout (5 sec), for simulating bad connection I'm using Network link conditioner

@samueladekunle

This comment has been minimized.

Copy link

samueladekunle commented Sep 12, 2018

The abortcontroller-polyfill works

A code snippet:

import "abortcontroller-polyfill";

class App extends React.Component {
    constructor() {
        const AbortController = window.AbortController;
        this.controller = new AbortController();
        this.signal = this.controller.signal;
    }
    componentDidMount() {
        const url = "https://myurl.com";
        const signal = this.signal;

        fetch(url, { signal })
        .then(res => res.json())
        .then(json => console.log(json))
        .catch(err => {
            // You can catch the error
            // thrown by the polyfill here.
            if (err.name == "AbortError") {
                console.log("Fetch Aborted");
            } else {
               //Catch other errors.
            }
        });
    }
    componentWillUnmount() {
        this.controller.abort();
    }
    /*--Rest of the code.--*/
}
@chmartinez

This comment has been minimized.

Copy link

chmartinez commented Oct 1, 2018

@samueladekunle you're using window.AbortController... is that intended?
In my case (using react-native v0.54.4) the abortcontroller's polyfill only works if I use its internal abortableFetch and AbortController implementations. Why? Because the polyfill works like this: if it founds a fetch object, it uses it. Otherwise, it uses own implementation.

So, to put it simply:

  • v0.54 uses whatwg-fetch if present (https://github.com/facebook/react-native/blob/0.54-stable/Libraries/Network/fetch.js#L19)
  • whatwg-fetch does not implement AbortController whatsoever and its fetch implementation is not compliant with the new spec (at least, v1.0.0 which is the one RN 0.54.4 uses).
  • abortcontroller-polyfill is implementing the AbortController stuff but if your code is using the fetch from whatwg-fetch` it's not gonna work. Hence, you need to use the polyfill's fetch.

Apparently, this issue should not happen with react-native 0.57 since whatwg-fetch was remove with this commit but I'm not 100% sure.

@m-vdb

This comment has been minimized.

Copy link

m-vdb commented Oct 2, 2018

$ npm ls whatwg-fetch
└─┬ react-native@0.57.0
  └─┬ fbjs@0.8.17
    └─┬ isomorphic-fetch@2.2.1
      └── whatwg-fetch@3.0.0
@arthurfranca

This comment has been minimized.

Copy link

arthurfranca commented Oct 3, 2018

I think the polyfill works as expected on RN 0.57. But sometimes, the abort event is received after the fetch promise has already resolved and won the Promise.race.
Probably because of using setTimeout that places the dispatch event on a queue.

One way to get around this is checking for controller.signal.aborted flag if you are no longer interested in the response. (e.g. the component is unmounted)

@Jyrno42 Jyrno42 referenced this issue Nov 22, 2018

Closed

Abortable requests #34

6 of 6 tasks complete
@hyochan

This comment has been minimized.

Copy link
Contributor

hyochan commented Dec 18, 2018

How do you solve the jest mocking when using @giacomocerquone solution?
image

I've tried to mock AbortController like below and won't work.

export default class AbortController {
  constructor() {
    this.controller = new AbortController();
  }
}
@Jyrno42

This comment has been minimized.

Copy link
Contributor

Jyrno42 commented Dec 31, 2018

Apparently, this issue should not happen with react-native 0.57 since whatwg-fetch was remove with this commit but I'm not 100% sure.

The polyfill in that commit does not contain any logic for Abort controllers so I do not think it works on latest rn as well (since the vendored file is based on 1.0.0 of whatwg-fetch).

Jyrno42 added a commit to Jyrno42/rn-tg-resources-tester that referenced this issue Dec 31, 2018

Add aborting test (not passing)
see facebook/react-native#18115

what i tried:

- using fetch patch from abortcontroller polyfill
  - 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
  - did not get it to work (weird error inside whatwg-fetch)
- patching react-native to use cross-fetch (by changing react-native/Libraries/Network/fetch.js)
  - did not get it to work (weird error inside cross-fetch)
- removing vendored whatwg-fetch from react-native source code (so the app loads real whatwg-fetch)
  - did not work
@TimurAsayonok

This comment has been minimized.

Copy link

TimurAsayonok commented Jan 15, 2019

Any updates of this?
Have same problem. I have tried to use new version of whatwg-fetch 3.0.0 with Aborting fetch, and it's work but, when we create new build it will crash. Because they change code in 3.0.0 for browsers.

@chmartinez can you give example how we can you abortableFetch from abortcontroller-polyfill

@TimurAsayonok

This comment has been minimized.

Copy link

TimurAsayonok commented Jan 16, 2019

So, I try to use cross-fetch instead latest version of whatwg-fetch

Upd. Looks like it is working. And what I have done:

  1. Install cross-fetch
  2. Install abortcontroller-polyfill for using AbortController()
  3. import fetch like import fetch from 'cross-fetch';
  4. import abortcontroller-polyfill like import "abortcontroller-polyfill"
  5. create signal for fetch:
const AbortController = window.AbortController;
this.controller = new AbortController();
this.signal = this.controller.signal;
  1. use signal from step 5) in your fetch fetch(url, {signal}). This fetch will be from cross-fetch
@giacomocerquone

This comment has been minimized.

Copy link
Author

giacomocerquone commented Apr 14, 2019

I wrote an article for all the people that were asking me to shed some light about this matter: https://blog.giacomocerquone.com/aborting-fetch-react-native/

In the next one I will give you some ready to use code to reject requests, but this time instead of giving you code I wanted to explain what is going on and how and why is useless to use polyfills in react native as of now.

Enjoy, hope I did a good thing!
As I wrote in the post, in the next article I will share with you my simple and short piece of code that I use to make requests that implements fetch rejection with few lines of code among other things

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.