React.js and Axios

ReactJS, the popular JavaScript library, excels at building dynamic and interactive user interfaces. And if you want to handle data fetching from servers using React this is where Axios comes in. Axios offering a powerful and convenient solution for making HTTP requests in your React applications.

What is Axios?

Axios is a lightweight HTTP client library built on top of the XMLHttpRequest (XHR) API. It simplifies making API requests with a clean and promise-based syntax, making your code more readable and maintainable.

Why Use Axios with React?

While alternatives like Fetch API exist, Axios provides several advantages:

  • Simpler Syntax: Axios offers a simpler and more intuitive syntax compared to Fetch API, making it easier to write and understand code.

  • Interceptors: Axios allows you to intercept requests and responses, enabling powerful features like authentication handling, error logging, and progress tracking.

  • Cancelation: You can easily cancel ongoing requests with Axios, improving user experience and resource management.

  • Transform Request & Response Data: Axios allows you to transform request and response data before sending and receiving, respectively. This helps in data manipulation and formatting.

Getting Started with Axios in React

Here's a quick guide to using Axios in your React project:

1. Install Axios:

npm install axios

2. Import Axios:

import axios from 'axios';

3. Make HTTP Requests:

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

// Post data
axios.post('https://api.example.com/data', {
  name: 'John Doe',
  email: 'johndoe@example.com'
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

4. Using Axios in React Components:

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const fetchData = async () => {
    try {
      const response = await axios.get('https://api.example.com/data');
      setData(response.data);
    } catch (error) {
      setError(error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      {data && <p>Data: {data.name}</p>}
      {error && <p>Error: {error.message}</p>}
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
};

This example demonstrates fetching data from an API and displaying it conditionally based on the response. It also handles potential errors.

Beyond the Basics

Axios offers advanced features like:

  • Transforming data: You can use interceptors to transform request and response data, such as converting JSON to objects.

  • Handling errors: Implement custom error handling logic using interceptors or the catch block in promises.

  • Canceling requests: Cancel ongoing requests using the CancelToken API, particularly useful for long-running requests.

Here are some scenarios illustrating how React and Axios work together in real-world applications:

Building a Blog with Content Management System (CMS) Integration:

  • Scenario: You're building a blog website where users can view articles. You have a separate CMS where articles are created and edited.

  • React's role: React handles rendering the user interface, displaying lists and details of articles.

  • Axios' role: Axios makes requests to the CMS API to:

    • Fetch a list of articles at initial load and on pagination.

    • Fetch individual article details when a user clicks on a specific article.

    • (Optional) Send data to create or update articles through forms (handled by other libraries like Formik).

Here's an example of using React and Axios in a blog website scenario:

1. Folder Structure:

- src
  - components
    - Article.js
    - ArticleList.js
  - App.js
  - api.js

2. api.js:

// api.js
import axios from 'axios';

const baseUrl = 'https://your-cms-api.com/api/';

export const fetchArticles = (page = 1) => {
  return axios.get(`${baseUrl}articles?page=${page}`);
};

export const fetchArticle = (id) => {
  return axios.get(`${baseUrl}articles/${id}`);
};

This file defines functions for fetching a list of articles and a single article by ID using Axios.

3. ArticleList.js:

// ArticleList.js
import React, { useState, useEffect } from 'react';
import { fetchArticles } from '../api';

const ArticleList = () => {
  const [articles, setArticles] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchMoreArticles = async () => {
    setLoading(true);
    try {
      const response = await fetchArticles(currentPage + 1);
      setArticles(articles.concat(response.data));
      setCurrentPage(currentPage + 1);
    } catch (error) {
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const fetchInitialArticles = async () => {
      setLoading(true);
      try {
        const response = await fetchArticles();
        setArticles(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchInitialArticles();
  }, []);

  return (
    <div>
      {error ? (
        <p>Error: {error.message}</p>
      ) : loading ? (
        <p>Loading...</p>
      ) : (
        <ul>
          {articles.map((article) => (
            <li key={article.id}>
              <a href={`/article/${article.id}`}>{article.title}</a>
            </li>
          ))}
        </ul>
      )}
      <button onClick={fetchMoreArticles} disabled={loading}>
        Load More
      </button>
    </div>
  );
};

export default ArticleList;

This component handles fetching and displaying a list of articles. It uses the fetchArticles function from api.js and handles loading, error, and pagination states.

4. Article.js:

// Article.js
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { fetchArticle } from '../api';

const Article = () => {
  const { id } = useParams();
  const [article, setArticle] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchArticleDetails = async () => {
      setLoading(true);
      try {
        const response = await fetchArticle(id);
        setArticle(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchArticleDetails();
  }, [id]);

  return (
    <div>
      {error ? (
        <p>Error: {error.message}</p>
      ) : loading ? (
        <p>Loading...</p>
      ) : (
        <div>
          <h2>{article.title}</h2>
          <p>{article.content}</p>
        </div>
      )}
    </div>
  );
};

export default Article;

5. App.js:

// App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Article

More info:

How To Use Axios with React

A Comprehensive Guide to Making HTTP Requests with Axios in React

Axios in React: A Guide for Beginners