Skip to content

Commit 5730e0c

Browse files
hramosMorgan Pretty
authored andcommitted
Networking Guide
Summary: Simplified Networking Guide, based on the old Network polyfill doc. This guide strongly recommends using fetch, while still informing the user about React Native's support for other libraries. In order to provide an actual working networking example, a `movies.json` file is added at the root of the site, allowing the user to fetch a small blob of JSON: ``` fetch('http://facebook.github.io/react-native/movies.json') ``` ![networking](https://cloud.githubusercontent.com/assets/165856/16321804/d2bd7c6a-3953-11e6-9fc5-30baaa38d7a4.png) Closes facebook#8381 Differential Revision: D3479018 Pulled By: lacker fbshipit-source-id: 1f2078bf2414a13f7f77d5af55b08948909093a3
1 parent 722e0a1 commit 5730e0c

File tree

2 files changed

+67
-84
lines changed

2 files changed

+67
-84
lines changed

docs/Basics-Network.md

Lines changed: 56 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
---
22
id: basics-network
3-
title: Network
3+
title: Networking
44
layout: docs
55
category: The Basics
66
permalink: docs/network.html
77
next: more-resources
88
---
99

10-
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.
10+
Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may simply need to fetch a chunk of static content from another server.
1111

12-
## Fetch
12+
## Using Fetch
1313

14-
[fetch](https://fetch.spec.whatwg.org/) 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.
14+
React Native provides the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for your networking needs. Fetch will seem familiar if you have used `XMLHttpRequest` or other networking APIs before. You may refer to MDN's guide on [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) for additional information.
1515

16-
#### Usage
16+
#### Making requests
17+
18+
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
1719

1820
```js
19-
fetch('https://mywebsite.com/endpoint/')
21+
fetch('https://mywebsite.com/mydata.json')
2022
```
2123

22-
Include a request object as the optional second argument to customize the HTTP request:
24+
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
2325

2426
```js
2527
fetch('https://mywebsite.com/endpoint/', {
@@ -35,74 +37,46 @@ fetch('https://mywebsite.com/endpoint/', {
3537
})
3638
```
3739

38-
#### Async
40+
Take a look at the [Fetch Request docs](https://developer.mozilla.org/en-US/docs/Web/API/Request) for a full list of properties.
41+
42+
#### Handling the response
3943

40-
`fetch` returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that can be processed in two ways:
44+
The above examples show how you can make a request. In many cases, you will want to do something with the response.
4145

42-
1. Using `then` and `catch` in synchronous code:
46+
Networking is an inherently asynchronous operation. Fetch methods will return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that make it straightforward to write code that works in an asynchronous manner:
4347

4448
```js
45-
fetch('https://mywebsite.com/endpoint.php')
46-
.then((response) => response.text())
47-
.then((responseText) => {
48-
console.log(responseText);
49-
})
50-
.catch((error) => {
51-
console.warn(error);
52-
});
49+
getMoviesFromApiAsync() {
50+
return fetch('http://facebook.github.io/react-native/movies.json')
51+
.then((response) => response.json())
52+
.then((responseJson) => {
53+
return responseJson.movies;
54+
})
55+
.catch((error) => {
56+
console.error(error);
57+
});
58+
}
5359
```
54-
2. Called within an asynchronous function using ES7 `async`/`await` syntax:
60+
61+
You can also use ES7's `async`/`await` syntax in React Native app:
5562

5663
```js
57-
class MyComponent extends React.Component {
58-
...
59-
async getUsersFromApi() {
60-
try {
61-
let response = await fetch('https://mywebsite.com/endpoint/');
62-
let responseJson = await response.json();
63-
return responseJson.users;
64-
} catch(error) {
65-
// Handle error
66-
console.error(error);
67-
}
64+
async getMoviesFromApi() {
65+
try {
66+
let response = await fetch('http://facebook.github.io/react-native/movies.json');
67+
let responseJson = await response.json();
68+
return responseJson.movies;
69+
} catch(error) {
70+
console.error(error);
6871
}
69-
...
7072
}
7173
```
7274

73-
- Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently
75+
Don't forget to catch any errors that may be thrown by `fetch`, otherwise they will be dropped silently.
7476

75-
## WebSocket
77+
### Using Other Networking Libraries
7678

77-
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
78-
79-
```js
80-
var ws = new WebSocket('ws://host.com/path');
81-
82-
ws.onopen = () => {
83-
// connection opened
84-
ws.send('something');
85-
};
86-
87-
ws.onmessage = (e) => {
88-
// a message was received
89-
console.log(e.data);
90-
};
91-
92-
ws.onerror = (e) => {
93-
// an error occurred
94-
console.log(e.message);
95-
};
96-
97-
ws.onclose = (e) => {
98-
// connection closed
99-
console.log(e.code, e.reason);
100-
};
101-
```
102-
103-
## XMLHttpRequest
104-
105-
XMLHttpRequest API is implemented on-top of [iOS networking apis](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) and [OkHttp](http://square.github.io/okhttp/). 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](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
79+
The [XMLHttpRequest API](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) is built in to React Native. This means that you can use third party libraries such as [frisbee](https://github.com/niftylettuce/frisbee) or [axios](https://github.com/mzabriskie/axios) that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
10680

10781
```js
10882
var request = new XMLHttpRequest();
@@ -118,38 +92,36 @@ request.onreadystatechange = (e) => {
11892
}
11993
};
12094

121-
request.open('GET', 'https://mywebsite.com/endpoint.php');
95+
request.open('GET', 'https://mywebsite.com/endpoint/');
12296
request.send();
12397
```
12498

125-
You can also use -
99+
> The security model for XMLHttpRequest is different than on web as there is no concept of [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) in native apps.
100+
101+
## WebSocket Support
102+
103+
React Native supports [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), a protocol which provides full-duplex communication channels over a single TCP connection.
126104

127105
```js
128-
var request = new XMLHttpRequest();
106+
var ws = new WebSocket('ws://host.com/path');
129107

130-
function onLoad() {
131-
console.log(request.status);
132-
console.log(request.responseText);
108+
ws.onopen = () => {
109+
// connection opened
110+
ws.send('something');
133111
};
134112

135-
function onTimeout() {
136-
console.log('Timeout');
137-
console.log(request.responseText);
113+
ws.onmessage = (e) => {
114+
// a message was received
115+
console.log(e.data);
138116
};
139117

140-
function onError() {
141-
console.log('General network error');
142-
console.log(request.responseText);
118+
ws.onerror = (e) => {
119+
// an error occurred
120+
console.log(e.message);
143121
};
144122

145-
request.onload = onLoad;
146-
request.ontimeout = onTimeout;
147-
request.onerror = onError;
148-
request.open('GET', 'https://mywebsite.com/endpoint.php');
149-
request.send();
123+
ws.onclose = (e) => {
124+
// connection closed
125+
console.log(e.code, e.reason);
126+
};
150127
```
151-
152-
153-
Please follow the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) for a complete description of the API.
154-
155-
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](https://github.com/niftylettuce/frisbee) or [axios](https://github.com/mzabriskie/axios) directly from npm.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"title": "The Basics - Networking",
3+
"description": "Your app fetched this from a remote endpoint!",
4+
"movies": [
5+
{ "title": "Star Wars", "releaseYear": "1977"},
6+
{ "title": "Back to the Future", "releaseYear": "1985"},
7+
{ "title": "The Matrix", "releaseYear": "1999"},
8+
{ "title": "Inception", "releaseYear": "2010"},
9+
{ "title": "Interstellar", "releaseYear": "2014"}
10+
]
11+
}

0 commit comments

Comments
 (0)