react-native/docs/Network.md
grgmo d09cd62011 Add support for ontimeout and onerror handler when using XMLHttpRequest for Android and iOS
Summary:Currently React-Native does not have `ontimeout` and `onerror` handlers for [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest). This is an extension to [No timeout on XMLHttpRequest](https://github.com/facebook/react-native/issues/4648).

With addition to two handlers, both Android and iOS can now handle `ontimeout` if request times out and `onerror` when there is general network error.

**Test plan**

Code has been tested on both Android and iOS with [Charles](https://www.charlesproxy.com/) by setting a breakpoint on the request which fires `ontimeout` when the request waits beyond `timeout` time and `onerror` when there is network error.

**Usage**

JavaScript -

```
var request = new XMLHttpRequest();

function onLoad() {
    console.log(request.status);
};

function onTimeout() {
    console.log('Timeout');
};

function onError() {
    console.log('General network error');
};

request.onload = onLoad;
request.ontimeout = onTimeout;
request.onerr
Closes https://github.com/facebook/react-native/pull/6841

Differential Revision: D3178859

Pulled By: lexs

fb-gh-sync-id: 30674570653e92ab5f7e74bd925dd5640fc862b6
fbshipit-source-id: 30674570653e92ab5f7e74bd925dd5640fc862b6
2016-04-15 05:17:21 -07:00

4.2 KiB

id title layout category permalink next
network Network docs Polyfills docs/network.html timers

One of React Native's goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change anything, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example.

Fetch

fetch is a better networking API being worked on by the standards committee and is already available in Chrome. It is available in React Native by default.

Usage

fetch('https://mywebsite.com/endpoint/')

Include a request object as the optional second argument to customize the HTTP request:

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

Async

fetch returns a Promise that can be processed in two ways:

  1. Using then and catch in synchronous code:
fetch('https://mywebsite.com/endpoint.php')
  .then((response) => response.text())
  .then((responseText) => {
    console.log(responseText);
  })
  .catch((error) => {
    console.warn(error);
  });
  1. Called within an asynchronous function using ES7 async/await syntax:
class MyComponent extends React.Component {
  ...
  async getUsersFromApi() {
    try {
      let response = await fetch('https://mywebsite.com/endpoint/');
      let responseJson = await response.json();
      return responseJson.users;
    } catch(error) {
      // Handle error
      console.error(error);
    }
  }
  ...
}
  • Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently

WebSocket

WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something');
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

XMLHttpRequest

XMLHttpRequest API is implemented on-top of iOS networking apis. The notable difference from web is the security model: you can read from arbitrary websites on the internet since there is no concept of CORS.

var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
  if (request.readyState !== 4) {
    return;
  }

  if (request.status === 200) {
    console.log('success', request.responseText);
  } else {
    console.warn('error');
  }
};

request.open('GET', 'https://mywebsite.com/endpoint.php');
request.send();

You can also use -

var request = new XMLHttpRequest();

function onLoad() {
    console.log(request.status);
    console.log(request.responseText);
};

function onTimeout() {
    console.log('Timeout');
    console.log(request.responseText);
};

function onError() {
    console.log('General network error');
    console.log(request.responseText);
};

request.onload = onLoad;
request.ontimeout = onTimeout;
request.onerror = onError;
request.open('GET', 'https://mywebsite.com/endpoint.php');
request.send();

Please follow the MDN Documentation for a complete description of the API.

As a developer, you're probably not going to use XMLHttpRequest directly as its API is very tedious to work with. But the fact that it is implemented and compatible with the browser API gives you the ability to use third-party libraries such as frisbee or axios directly from npm.