Many applications require networking to load resources from remote URLs. In order to fetch data from a server or make a POST
,PUT
or DELETE
request to an API. In this article, we will discuss how you can fetch data and display it in your application.
Networking in React Native can be done in multiple ways:
Let's now deep dive into how to use these methods.
Fetch API
Fetch API is one of the most commonly used asynchronous methods as it comes wrapped with React Native.
Example:
fetch(YOUR_API_URL_HERE).then((response)=>{
console.log(response);
}).catch((error)=>{
console.log(error);
})
Some of the API calls require some request parameters to be sent along with them. These parameters could include the method
, credentials
, mode
, headers
, etc. So they can be sent as follows:
const data = {
method: 'GET',
credentials: 'same-origin',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
fetch(YOUR_API_URL_HERE, data).then((response)=>{
console.log(response);
}).catch((error)=>{
console.log(error);
})
Axios
Axios can be used as an alternative to Fetch API. It is compatible with node
, React
and React Native
.
To use axios
, one would require to install the Axios library with the help of one of the following commands:
npm install axios
yarn add axios
The API call using Axios would look as:
import axios from 'axios';
axios.get(YOUR_API_URL_HERE).then((response)=>{
console.log(response);
}).catch((error)=>{
console.log(error);
})
The request parameters can be sent as:
import axios from 'axios';
const data = {
credentials: 'same-origin',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
axios.get(YOUR_API_URL_HERE, data).then((response)=>{
console.log(response);
}).catch((error)=>{
console.log(error);
})
Conclusion
In this way, we can implement networking in react native.
Stay tuned for more such blogs!