How To Make API Calls in React.js/Next.js?

How To Make API Calls in React.js/Next.js?

ยท

3 min read

Introduction

In the World of Modern Web Development, integrating APIs into your React.js/Next.js applications has become a common practice. APIs allow you to fetch data from external sources, making your applications more Dynamic and Interactive. In this article, we'll explore the three most popular methods to make API calls.

  1. fetch API function

  2. the powerful axios library, and

  3. the asynchronous async/await approach.

So, let's dive in and learn how to harness the capabilities of these tools to enhance your React applications!

Fetch: The Native Way

The fetch API is built into modern browsers and provides a simple way to make asynchronous network requests. It returns a Promise that resolves the Response to the request.

Refer fetch API Documentation by clicking here.

  1. Making GET Requests-
fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => {
    // Handle the response data
  })
  .catch(error => {
    // Handle errors here
  });
  1. Making POST Requests-
fetch("https://api.example.com/submit", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ key: "value" })
})
  .then(response => response.json())
  .then(data => {
    // Handle the response data
  })
  .catch(error => {
    // Handle errors here
  });

Axios: The Versatile Choice

Axios is a popular third-party library that simplifies the process of making HTTP requests. It supports various features like request and response interceptors, automatic JSON parsing, and request cancellation.

Refer Axios documentation by clicking here.

Follow the below steps to get started with using Axios.

  1. Installing Axios-
npm install axios
  1. Making Requests with Axios-
  • Making GET Requests-
import axios from 'axios';

axios.get("https://api.example.com/data")
  .then(response => {
    const data = response.data;
    // Process the data
  })
  .catch(error => {
    // Handle errors
  });
  • Making POST Requests-
import axios from 'axios';

axios.post("https://api.example.com/submit", { key: "value" })
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });

Async/Await: The Clean Approach

Async/Await is a modern JavaScript feature that makes asynchronous code look and feel more like synchronous code. It's especially useful when working with Promises.

Refer async/await documentation by clicking here.

  1. Using Async/Await with Fetch-
async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    // Work with the data
  } catch (error) {
    // Handle errors
  }
}
  1. Using Async/Await with Axios-
import axios from 'axios';

async function fetchData() {
  try {
    const response = await axios.get("https://api.example.com/data");
    const data = response.data;
    // Process the data
  } catch (error) {
    // Handle errors
  }
}

In this article, we explored three methods for making API calls in React: using the native fetch function, the versatile axios library, and the cleaner async/await approach.

Each method has its strengths and use cases, so choose the one that best suits your project's requirements. Whether you're fetching data, sending data to a server, or handling errors, these techniques will empower you to create more dynamic and interactive React applications.

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer ๐Ÿค”!

ย