DEV Community

Cover image for How to Use Axios for Fetching Data in Frontend Applications
Rowsan Ali
Rowsan Ali

Posted on

How to Use Axios for Fetching Data in Frontend Applications

Axios is a popular promise-based HTTP client that simplifies making asynchronous requests to external APIs. Its clean API, built-in JSON transformation, and extensive configuration options make it a developer favorite for fetching data in your frontend applications. In this post, we’ll go through actionable steps and code examples to get you started with Axios in both vanilla JavaScript and modern frameworks like React.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

Table of Contents

  1. Introduction to Axios
  2. Getting Started and Installation
  3. Basic Usage Example
  4. Advanced Axios Techniques
  5. Actionable Steps to Integrate Axios
  6. Conclusion

Introduction to Axios

Axios is designed with simplicity in mind. Whether you're building a simple webpage or a complex single-page application, Axios can be easily integrated to handle GET, POST, PUT, DELETE, and other HTTP requests.

Key benefits of using Axios:

  • Promise-based: Works seamlessly with async/await for handling asynchronous operations.
  • Automatic JSON Data Transformation: Automatically transforms JSON data for easier use.
  • Browser and Node.js Compatibility: Run the same code on both client and server.
  • Interceptors: Modify requests or responses before they are handled by then/catch.
  • Built-In XSRF Protection: Enhances security for your applications.

Getting Started and Installation

Before making any HTTP requests, you need to install Axios. You can either use a package manager like npm/yarn or include it via a CDN.

Installation via npm or yarn

For a modern build setup, install Axios using npm:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Or using yarn:

yarn add axios
Enter fullscreen mode Exit fullscreen mode

Including via CDN

If you're working on a simpler project without a module bundler, include Axios directly using a CDN in your HTML file:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Basic Usage Example

Whether you are using Axios in vanilla JavaScript or within a framework, the steps remain similar. Let’s start with a simple GET request to fetch data from a JSON placeholder API.

Vanilla JavaScript Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Axios GET Request</title>
</head>
<body>
  <h1>Axios Data Fetching Example</h1>
  <div id="data"></div>

  <!-- Include Axios via CDN -->
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    // Making a GET request using Axios
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        const posts = response.data;
        let output = '<h2>Posts</h2>';
        posts.forEach(post => {
          output += `
            <div>
              <h3>${post.title}</h3>
              <p>${post.body}</p>
            </div>
          `;
        });
        document.getElementById('data').innerHTML = output;
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Using Async/Await in JavaScript

For cleaner code, consider using async/await to handle asynchronous operations:

async function fetchPosts() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    const posts = response.data;
    // Render posts or process data as needed.
    console.log('Posts:', posts);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchPosts();
Enter fullscreen mode Exit fullscreen mode

Advanced Axios Techniques

As you get comfortable with Axios, consider these advanced techniques:

Configuring a Base URL

If you often hit the same API endpoint, set up a base URL:

const api = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com'
});

// Then, you can make API calls without repeating the base URL, e.g.:
api.get('/posts')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

Using Axios Interceptors

Interceptors let you manipulate requests before they are sent and responses before they are processed.

// Request interceptor to add headers
axios.interceptors.request.use(config => {
  // You could append authorization tokens here
  config.headers.Authorization = 'Bearer your-token-here';
  return config;
}, error => {
  return Promise.reject(error);
});

// Response interceptor to handle errors globally
axios.interceptors.response.use(response => {
  return response;
}, error => {
  // You could show a user-friendly error message here
  console.error('Global error handler:', error);
  return Promise.reject(error);
});
Enter fullscreen mode Exit fullscreen mode

Sending POST Requests

For sending data to your backend, you can use Axios's post method:

const newPost = {
  title: 'Axios Post Example',
  body: 'This post was created with an Axios POST request!',
  userId: 1
};

axios.post('https://jsonplaceholder.typicode.com/posts', newPost)
  .then(response => {
    console.log('Post created:', response.data);
  })
  .catch(error => {
    console.error('Error creating post:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Actionable Steps to Integrate Axios

  1. Install Axios:

    • Use npm/yarn or include via CDN depending on your project setup.
  2. Import Axios in Your Project:

    • For module-based projects: import axios from 'axios';
    • For CDN usage, Axios will be available as a global variable.
  3. Make Basic GET Requests:

    • Start by fetching simple data from a public API to understand the basics.
    • Familiarize yourself with promise handling using .then() and .catch(), then explore async/await.
  4. Handle Errors Gracefully:

    • Implement proper error handling using .catch() or try-catch blocks with async/await.
    • Consider using interceptors to manage global error handling.
  5. Configure Common Settings:

    • Set up a base URL if your application interacts with one main API.
    • Customize global settings (like headers) by using Axios’ axios.create().
  6. Utilize Advanced Features:

    • Explore Axios interceptors for tasks such as adding authorization tokens or logging errors.
    • Experiment with other HTTP methods (POST, PUT, DELETE) to realize full CRUD functionality.
  7. Integrate into Your Framework:

    • If you’re using frameworks like React or Vue, incorporate Axios in your components or services.
    • In React, consider using Axios within the useEffect hook to fetch data on component mount.

React Example with Axios

Here’s a small example demonstrating how to fetch data within a React component:

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

function Posts() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Using an async function within useEffect
    const fetchPosts = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setPosts(response.data);
      } catch (err) {
        setError('Failed to fetch posts');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchPosts();
  }, []);

  if (loading) return <div>Loading posts...</div>;
  if (error) return <div>{error}</div>;

  return (
    <div>
      <h2>Posts</h2>
      {posts.map(post => (
        <div key={post.id} style={{ marginBottom: '1em' }}>
          <h3>{post.title}</h3>
          <p>{post.body}</p>
        </div>
      ))}
    </div>
  );
}

export default Posts;
Enter fullscreen mode Exit fullscreen mode

In this React example, Axios is used to retrieve posts during component initialization, with loading state management and error handling.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

Conclusion

Axios offers a clean, efficient way to perform HTTP requests in your frontend applications. It abstracts the complexity of handling lower-level network requests, allowing you to focus on displaying data and building features. By following the actionable steps above—installing Axios, making basic requests, handling errors, and integrating advanced techniques—you can seamlessly fetch data and build dynamic, data-driven applications. Happy coding!

Top comments (0)