Networking
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 need to fetch a chunk of static content from another server.
Using Fetch
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.
Making requests
In order to fetch content from an arbitrary URL, you can pass the URL to fetch:
fetch('https://mywebsite.com/mydata.json');
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:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Take a look at the Fetch Request docs for a full list of properties.
Handling the response
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 method will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
.then(response => response.json())
.then(json => {
return json.movies;
})
.catch(error => {
console.error(error);
});
};
You can also use the async / await syntax in a React Native app:
const getMoviesFromApiAsync = async () => {
try {
const response = await fetch(
'https://reactnative.dev/movies.json',
);
const json = await response.json();
return json.movies;
} catch (error) {
console.error(error);
}
};
Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.
- TypeScript
- JavaScript
By default, iOS enforces App Transport Security (ATS), requiring any HTTP connection to use HTTPS. If you need to fetch from a cleartext URL (one that begins with http), you must configure an ATS exception in your Info.plist file using NSAppTransportSecurity. It is recommended to add exceptions only for specific domains using NSExceptionDomains rather than disabling ATS globally (NSAllowsArbitraryLoads), as Apple's App Store review requires justification for disabling ATS. See Apple's documentation on Preventing Insecure Network Connections for more information.
On Android, as of API Level 28, clear text traffic is also blocked by default. This behaviour can be overridden by setting android:usesCleartextTraffic in the app manifest file.
Using Other Networking Libraries
The XMLHttpRequest API is built into 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.
const 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/');
request.send();
The security model for XMLHttpRequest is different than on web as there is no concept of CORS in native apps.
WebSocket Support
React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.
const ws = new WebSocket('ws://host.com/path');
ws.onopen = () => {
// connection opened
ws.send('something'); // send a message