Menu
fetch vs axios

Fetch vs. Axios: Choosing the Right

Shivangi Rajde 6 months ago 0 133

In the world of web development, making HTTP requests is a fundamental operation. Whether you’re fetching data from an API, sending data to a server, or performing other network-related tasks, you need a reliable tool to handle these operations. Two popular JavaScript libraries, Fetch and Axios.js, have emerged as go-to choices for developers when it comes to making HTTP requests. In this article, we’ll explore the key differences between Fetch and Axios.js, helping you make an informed decision on which one to use in your web projects.

Fetch: A Native JavaScript API

Fetch is a built-in web API in modern browsers that provides a simple and standardized way to make HTTP requests. It was introduced as part of the Fetch API specification, which is now supported by all major browsers, making it readily available for use in your web applications without the need for external dependencies.

Simplicity and Clarity: Fetch offers a clean and straightforward API for making HTTP requests. It uses promises, making asynchronous code more readable and maintainable. Here’s a basic example of how to use Fetch to make a GET request:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

No External Dependencies: Since Fetch is native to modern browsers, it doesn’t require any additional libraries or dependencies. This reduces the size of your project and simplifies the setup process.

Wide Browser Support: Fetch enjoys wide support among modern browsers, ensuring cross-compatibility without the need for polyfills.

Axios.js: A Powerful HTTP Client

Axios.js, on the other hand, is a popular JavaScript library specifically designed for making HTTP requests. It is widely used in both frontend and backend applications and offers several advantages over Fetch.

Promise-based: Like Fetch, Axios.js is promise-based, making it easy to write asynchronous code and handle HTTP requests elegantly. Here’s a simple Axios GET request:

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

Abstraction and Features: Axios.js abstracts many complexities of the HTTP request and response process. It provides features such as automatic JSON parsing, request cancellation, and interceptors for request and response manipulation.

Cross-Browser Compatibility: Axios.js is not limited to browsers and can be used in various JavaScript environments, including Node.js. This makes it an excellent choice for isomorphic (universal) applications that run on both the client and server.

Error Handling: Axios.js provides detailed error handling, making it easier to identify and handle different types of errors that may occur during HTTP requests.

To learn more about Axios read Making HTTP requests using Axios and Axios in React.

When to Choose Fetch or Axios.js

Now that we’ve discussed the differences between Fetch and Axios.js, the question arises: When should you use each one?

When to use fetch

  • Simplicity and minimalism are your top priorities, and you don’t want to introduce external dependencies.
  • You’re building a project that only targets modern browsers with Fetch support.
  • You prefer working with native browser features whenever possible.

When to use Axios

  • You require advanced features such as request interceptors, response transformers, or automatic request cancellation.
  • Cross-environment compatibility, including Node.js, is essential for your project.
  • You want robust error-handling capabilities to handle different HTTP response statuses gracefully.
  • You prefer a dedicated library with a strong community and extensive documentation.

Examples

Here are the examples of using both Fetch and Axios.js to make HTTP GET requests.

Using Fetch

// Example using Fetch to make a GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log('Fetch Example - Response:', data))
  .catch(error => console.error('Fetch Example - Error:', error));

Output in the console:

Fetch Example - Response: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio     reprehenderit",
  "body": "quia et suscipit\nsuscipit...distinctio\net quaerat distinctio ...voluptates repudiandae sit error\nvoluptatem ...consequuntur quis pariatur qui."
}

Using Axios.js

// Example using Axios.js to make a GET request
axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => console.log('Axios Example - Response:', response.data))
  .catch(error => console.error('Axios Example - Error:', error));

Output in Console:

Axios Example - Response: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit...distinctio\net quaerat distinctio ...voluptates repudiandae sit error\nvoluptatem ...consequuntur quis pariatur qui."
}

In both examples, we made a GET request to the same URL (https://jsonplaceholder.typicode.com/posts/1), which is a placeholder JSON API for testing. Both Fetch and Axios.js successfully retrieved the data, parsed the JSON response, and logged the result to the console.

These examples demonstrate that both Fetch and Axios.js are capable of making HTTP requests and handling the response data effectively. The choice between the two will depend on your project’s specific requirements and the features you need.

Using Fetch with React

Inside your component, you can use the fetch function to make a GET request to an API or server. Here’s an example:

import React, { useState, useEffect } from 'react';

function FetchExample() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((error) => console.error('Fetch in React - Error:', error));
  }, []); // Empty dependency array ensures the effect runs once (on mount)

  return (
    <div>
      {loading ? 'Loading...' : <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
}

export default FetchExample;

In this functional component, we use the useState hook to manage the component’s state. We initialize the data state to null and the loading state to true. We then use the useEffect hook to perform the Fetch request when the component mounts ([] as the dependency array ensures it only runs once).

Using Axios.js with React

In your React component file, import React and Axios. Make sure you have Axios installed in your project, you can install it using

npm install axios

or

yarn add axios

Here’s how you can use Axios.js with a functional component in React:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function AxiosExample() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts/1')
      .then((response) => {
        setData(response.data);
        setLoading(false);
      })
      .catch((error) => console.error('Axios in React - Error:', error));
  }, []); // Empty dependency array ensures the effect runs once (on mount)

  return (
    <div>
      {loading ? 'Loading...' : <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
}

export default AxiosExample;

In this functional component, we follow the same structure as the Fetch example. We use the useState hook to manage the data and loading states. We then use the useEffect hook to make the Axios GET request when the component mounts.

Conclusion

Both Fetch and Axios.js are powerful tools for making HTTP requests in JavaScript. Your choice between the two should depend on your project’s specific requirements and constraints. Fetch is a native and minimalist option that works well for simple use cases and modern browsers, while Axios.js provides additional features, robust error handling, and broader compatibility, making it a strong choice for more complex projects. Ultimately, understanding the differences and capabilities of each tool will enable you to make an informed decision and enhance your web development workflow.

Related articles

Making HTTP requests using Axios
How to asynchronously call APIs inside the useEffect hook?
Axios in React

– Advertisement – BuzzMag Ad
Written By

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *