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.
React Native provides the 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 for additional information.
In order to fetch content from an arbitrary URL, just pass the URL to fetch:
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:
Take a look at the Fetch Request docs for a full list of properties.
The above examples show how you can make a request. In many cases, you will want to do something with the response.
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
You can also use the proposed ES2017
await syntax in a React Native app:
Don't forget to catch any errors that may be thrown by
fetch, otherwise they will be dropped silently.
By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with
http) you will first need to add an App Transport Security exception. If you know ahead of time what domains you will need access to, it is more secure to add exceptions just for those domains; if the domains are not known until runtime you can disable ATS completely. Note however that from January 2017, Apple's App Store review will require reasonable justification for disabling ATS. See Apple's documentation for more information.
The XMLHttpRequest API is built in to React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
The security model for XMLHttpRequest is different than on web as there is no concept of CORS in native apps.
React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.
Your app can now display all sorts of data and you may soon need to organize this content into several screens. To manage the transition between these screens, you will need to learn about navigators.
You can edit the content above on GitHub and send us a pull request!