Mastering API Calls in React Native: A Comprehensive Guide with Fetch and Axios

DevNex Pro
4 min readAug 5, 2023

Introduction

As the demand for feature-rich and dynamic mobile applications continues to rise, integrating APIs into your React Native projects becomes crucial. APIs (Application Programming Interfaces) enable communication between different software applications, allowing you to fetch data from remote servers, authenticate users, and perform various backend operations. In this guide, we’ll explore two popular methods for making API calls in React Native: Fetch and Axios.

Section 1: The Fundamentals of API Calls

Before we dive into Fetch and Axios, let’s understand the fundamentals of making API calls in React Native. API calls involve sending HTTP requests to remote servers and handling the responses received. These responses usually contain data in formats like JSON or XML. In our examples, we’ll be working with JSON data.

Section 2: Making a GET API Call

Using Fetch:

Fetch is a built-in web API available in modern browsers and React Native. It allows you to make various types of network requests, including GET. Here’s how to make a GET request using Fetch:

fetch(‘https://api.example.com/data')

.then(response => response.json())

.then(data => {

// Handle the data here

console.log(data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

When you call the API, Fetch returns a Promise, which you can then use to handle the data and any potential errors.

Using Axios:

Axios is a popular JavaScript library that simplifies making HTTP requests. To use Axios, first, install it in your project:

npm install axios

Now, you can make a GET request using Axios:

import axios from ‘axios’;

axios.get(‘https://api.example.com/data')

.then(response => {

// Handle the data here

console.log(response.data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

Axios’s syntax is simple, and it automatically parses the response data, making it a preferred choice for many developers.

Section 3: Making a POST API Call

Using Fetch:

To make a POST request using Fetch, you need to provide additional options in the request. Let’s see how to do it:

const dataToSend = { username: ‘john_doe’, password: ‘secure_password’ };

fetch(‘https://api.example.com/login', {

method: ‘POST’,

headers: {

‘Content-Type’: ‘application/json’,

},

body: JSON.stringify(dataToSend),

})

.then(response => response.json())

.then(data => {

// Handle the response data here

console.log(data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

This example sends a POST request to the server with the specified data in JSON format.

Using Axios:

Axios simplifies making POST requests and automatically handles JSON serialization:

import axios from ‘axios’;

const dataToSend = { username: ‘john_doe’, password: ‘secure_password’ };

axios.post(‘https://api.example.com/login', dataToSend)

.then(response => {

// Handle the response data here

console.log(response.data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

Axios’s post method makes it convenient to send POST requests without manually handling JSON serialization.

Section 4: Making a PUT API Call

Using Fetch:

Making a PUT request using Fetch is similar to a POST request, but with a different HTTP method:

const dataToUpdate = { name: ‘John Doe’, age: 30 };

fetch(‘https://api.example.com/users/123', {

method: ‘PUT’,

headers: {

‘Content-Type’: ‘application/json’,

},

body: JSON.stringify(dataToUpdate),

})

.then(response => response.json())

.then(data => {

// Handle the response data here

console.log(data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

Using Axios:

Axios simplifies making PUT requests just like POST:

import axios from ‘axios’;

const dataToUpdate = { name: ‘John Doe’, age: 30 };

axios.put(‘https://api.example.com/users/123', dataToUpdate)

.then(response => {

// Handle the response data here

console.log(response.data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

Section 5: Making a PATCH API Call

Using Fetch:

Making a PATCH request using Fetch follows the same pattern as POST and PUT:

const dataToPatch = { age: 31 };

fetch(‘https://api.example.com/users/123', {

method: ‘PATCH’,

headers: {

‘Content-Type’: ‘application/json’,

},

body: JSON.stringify(dataToPatch),

})

.then(response => response.json())

.then(data => {

// Handle the response data here

console.log(data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

Using Axios:

Axios simplifies making PATCH requests:

import axios from ‘axios’;

const dataToPatch = { age: 31 };

axios.patch(‘https://api.example.com/users/123', dataToPatch)

.then(response => {

// Handle the response data here

console.log(response.data);

})

.catch(error => {

// Handle errors

console.error(‘Error:’, error);

});

Section 6: Pros and Cons Comparison

Each method has its strengths and weaknesses:

Fetch:

  • Pros: Built-in, lightweight, no additional setup required.
  • Cons: Fewer features compared to Axios, a bit verbose in syntax.

Axios:

  • Pros: Feature-rich, easy-to-use, automatic JSON parsing.
  • Cons: Slightly larger bundle size due to the external dependency.

Section 7: Best Practices and Conclusion

To ensure efficient and reliable API calls, follow these best practices:

  • Always handle errors to prevent app crashes.
  • Use async/await for cleaner asynchronous code.
  • Implement loading indicators to enhance user experience.
  • Consider data caching for improved performance.

In conclusion, API integration is a vital skill for React Native developers. We explored both Fetch and Axios methods for making API calls, covering GET, POST, PUT, and PATCH requests. Each method has its advantages, and choosing between them depends on your project’s specific requirements. By mastering API calls, you can build powerful, data-driven React Native applications.

Happy coding and happy API calling!

--

--

DevNex Pro

Senior Developer | Javascript, React.js, React Native, Node.js enthusiast | Crafting seamless web & mobile experiences | Tech explorer & code enthusiast 🚀