Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Using Fetch 
2.1.
Making requests
2.2.
Handling the response data
3.
Frequently Asked Questions
3.1.
What is an API, and what do you mean by API integration? 
3.2.
What is asynchronous programming?
3.3.
State the difference between the POST and PUT HTTP requests. 
4.
Conclusion
Last Updated: Mar 27, 2024

React Native API Integration

Author GAZAL ARORA
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

React Native is an open-source javascript framework used for building android/iOS applications. An API (application programming interface) is a medium that connects two or more applications. By "connects two or more applications," I mean that APIs facilitate the exchange of information b/w two or more applications. 

For example, GoIbibo aggregates data from various hotels, airlines, buses, and trains by calling their APIs. Now, we will see how to make an API call to retrieve some data from a remote server. 


Click on the following link to read further: Hooks in React JS

Using Fetch 

For your networking needs (making HTTP(S) requests), React Native provides the Fetch API. Data is fetched using a global method called 'fetch().' This method is asynchronous. It simply takes one argument in its basic form: the URL of the data to be retrieved. We can use it to fetch data asynchronously and then perform operations on it once the fetch is complete. 

Refer to MDN's guide on Using Fetch for more information.

Making requests

You can pass the URL as an argument in the fetch method:

fetch('https://jsonplaceholder.typicode.com/todos/1');

Response: 

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Fetch optionally accepts a second argument that can be used to customize the HTTP request. For example, you may want to add a body and headers to make a POST request.

fetch('https://reqres.in/api/users', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Gazal',
    job: 'Software engineer'
  })
});

Response: 

{
  "name": "Gazal",
  "job": "Software engineer",
  "id": "800",
  "createdAt": "2022-05-23T17:32:21.326Z"
}

One can use Postman to test the APIs that are mentioned above. To know more about the fetch method, read Fetch Request docs.

Handling the response data

We learned how to make GET and POST requests from the above examples. You can try PUT and DELETE requests on yourself. Once a request is made, eventually, we get a response. It is crucial to keep in mind that network calls are behaviorally asynchronous. The fetch method will return a Promise that helps us write asynchronous code easily. 

This is an example of asynchronous code. We have used async-await

const createNewUser = async(userName, userJob) => {
  try {
      const response = await fetch('https://reqres.in/api/users', {
          method: 'POST',
          headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json'
          },
          body: JSON.stringify({
              name: userName,
              job: userJob
          })
      });
      const json = await response.json();
      return json;
  } catch (error) {
      console.error(error);
  }
};

Error handling becomes super essential when developing large applications. 

To create a blank React native app, follow the official documentation.

Once a blank app is created, replace the App.js file with the following code. In the following code, we have made an API call to fetch data from a remote URL and show it on the frontend.

import * as React from 'react';
import { Text, View } from 'react-native';
export default class App extends React.Component {
  state = {
      data: '',
  };
  componentDidMount() {
      fetch('https://jsonplaceholder.typicode.com/posts/1')
          .then(response => response.json())
          .then(json => {
              this.setState({
                  data: json.body,
              });
          })
          .catch(error => {
              console.error(error);
          });
  }
  render() {
      return (
      <View style = {
              {
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'center'
              }
          } >
          <Text> { this.state.data } </Text>
          </View>
      );
  }
}

Start the app by running the following command on your terminal/command prompt. 

npm start

After running the command, you will get options to run the app on android/iOS/web. You need to set up an emulator if you want to run the app on android/iOS. Below is a screenshot showing what the web app looks like. 

Also see,  React Native Reanimated

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What is an API, and what do you mean by API integration? 

An API is an interface that allows multiple applications to exchange data. API integration means using APIs to fetch data from a remote URL and using it in your app as per your business requirement. 

What is asynchronous programming?

It is a technique that facilitates long-running tasks in the background and does not halt the whole process. We don't have to wait for a large task that takes time. A mechanism runs such tasks in the background so that the entire process is not paused due to a single task. Instead, the next line of code is executed. Fetching data from a database and making API calls are asynchronous. 

State the difference between the POST and PUT HTTP requests. 

POST is used when you want to create a new object in the database. For example, if someone registers on your website, you want to create a new user and add it to the database. Whereas you use PUT if you wish to modify some details of an existing user (like residential address, profession). 

Conclusion

In this blog, we learned about APIs and how to use them to fetch data from a remote URL and use that data in our React-native application. We learned about the fetch API. We saw an example of integrating an API in our react application. We learned about some basic javascript concepts like promises and async-await, which helps us write asynchronous code very easily.

You can also consider our React Js Course to give your career an edge over others.

Happy Coding!

Live masterclass