I built an app where the port number of the API can be configured. The user can set a new port number. If the port number is not valid, the API call will hang for 100 seconds! I wanted to introduce a feature where the API call times out in 10 seconds.

Before I started to work on this task, I did not know that the fetch specification does not have a timeout option. I started looking for short-cuts and stumbled upon an issue in the react-native repo. The work-around was to copy the react-native fetch, set timeout on xhr and handle the callback. The react-native-fetch-polyfill npm package does exactly that.

Other developers were using react-native-fetch-polyfill from the github repo. No one published the package to the NPM registry. I cloned the repo and did a npm publish. The package published successfully.

Use the package from the NPM registry.

Use the fetch from the package.

The loading state is toggled when fetch is used.

Without react-native-fetch-polyfill, it is very difficult to set a timeout on the fetch request. There are other work-around involving setTimeout. But these work-around are cumbersome to implement.

The issue to add timeout to fetch is open in the repo since January 2015. It is unlikely that it gets resolved anytime soon. In the meantime, react-native-fetch-polyfill package does the work. The react-native team should fix the timeout issue in fetch in a similar way without waiting for a fix from whatwg-fetch.

It is nice to see my name in the NPM registry. The credit for writing the package goes to Atticus White. Some day, I hope to write a generic component which gets published in NPM registry.

react-native-fetch-polyfill in npm registry
react-native-fetch-polyfill in npm registry
Setting a timeout for fetch using react-native-fetch-polyfill
Tagged on: