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 the fetch() method to perform network call operations.
API Calls in React Native using Fetch():-
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.
Let’s explain it with code:-
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 which kind of API you are executing as GET API, POST API or any other.
headers:- At the headers key, you need to define your headers 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 we call then() method to get the response.
In addition, Once you’ve defined your API call using the fetch()
method, the next step is to execute the request and set the retrieved data in your components like flatlist etc.
Code example for API calling:-
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); }); } |
API Calls in React Native Using Axios
While the Fetch API is built into JavaScript and works perfectly for most use cases, many developers prefer using Axios for its simplicity and additional features.
Axios is a promise-based HTTP client that simplifies the process of making HTTP requests and handling responses.
Why Use Axios?
- Simplified Syntax: Axios provides a more straightforward syntax compared to Fetch, especially for handling request and response transformations.
- Automatic JSON Data Transformation: Axios automatically transforms JSON data, meaning you don’t have to call
response.json()
as you do with Fetch. - Error Handling: Axios has better error-handling capabilities, making it easier to catch and handle errors.
- Request Cancellation: Axios supports request cancellation, which is useful in scenarios like avoiding memory leaks during component unmounts.
- Interceptors: You can set up request and response interceptors for logging, authentication, and more.
Common Use Case for Axios
Axios is particularly useful when dealing with applications that require frequent API interactions, such as:
- User Authentication: When handling login/logout requests, Axios makes it easy to manage tokens and refresh them as needed.
- Fetching and Submitting Data: In applications like dashboards or forms where data needs to be fetched, displayed, and updated frequently, Axios simplifies these processes with its intuitive API.
Here Is The Reference Video for the Api Calling:
API Calls in React Native
This is the reference video for Sign-in API calling.
In the video, you will learn how to implement API requests for user authentication, ensuring a smooth and secure sign-in process in your React Native application.
The tutorial covers everything from making the API call using the fetch()
method to handling responses and managing user state effectively.
Conclusion
In this blog, we explored how to make API calls in React Native using the fetch()
method, which simplifies the process of communicating with remote servers.
By leveraging fetch()
, we can easily perform network operations such as sending data, retrieving information, and handling responses, which are essential for building dynamic applications.
The provided code snippet illustrates a straightforward implementation, showcasing how to manage requests, parse JSON responses, and handle errors effectively.
Thank you for reading! ❤️
You can also check other blogs from here.