Updated 6 March 2021
In React-native we don’t need to import any third-party library to make API network calls like Retrofit or Volly. In React-native we use fetch() method to perform network calls operations.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global method fetch() that provides an easy, logical way to fetch resources asynchronously across the network.
1 2 3 4 5 6 7 8 9 10 11 12 |
fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'CustomHeaders': 'customHeaderValue' }, body: JSON.stringify({ 'your_key1': 'your_value1', 'your_key2': 'your_value2', }), }); |
In the fetch() method we have two parameters.
1- API URL:- In my case “https://mywebsite.com/endpoint/” this URL is gonna be my API URL.
2- JSON Object:- After the API URL we have a JSON object which contains several keys like method, headers, and body.
NOTE–> Please make sure that the key’s name must be the same as it is written in the code. Because it is predefined keys.
method:- At Method key, you need to define that which kind of API you are executing as GET API, POST API or any other.
headers:- At headers key, you need to define your headers like in my case I am passing three headers Accept, Content-type, and CustomHeaders.
body:- At body key, you need to send the params in that key. Like I am hitting a POST request so it can contain params also so in that key put the JSON data that you want to Post.
After that, you need to call another method to get the response.
then():- We use then() method an call back. When we close the fetch() method brackets then we call then() method to get the response.
1 2 3 4 5 6 7 8 9 10 11 12 |
function _callApi() { return fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'CustomHeaders': 'customHeaderValue' }, body: JSON.stringify({ 'your_key1': 'your_value1', 'your_key2': 'your_value2', }), }) .then((response) => response.json()) .then((responseJson) => { return responseJson; }) .catch((error) => { console.error(error); }); } |
Now we got the response in responseJson.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.