Onjsdev

Share


Axios instance in react

How To Create An Axios Instance in React


By onjsdev

Dec 7th, 2023

It's important to make HTTP requests easily in our React applications. Axios provides several ways to do this. One of these is the ability to create an Axios instance with predefined configurations so we don't have to add configuration information to the request each time.

How To Create An Axios Instance

To get started, create an Axios instance in a separate file. This file could be named axiosinstance.js.

Import Axios and create an instance:

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

const instance = axios.create({
  baseURL: 'https://api.example.com', // Replace with your API base URL
  timeout: 5000, // Set a timeout for requests (optional)
  headers: {
    'Content-Type': 'application/json',
    // Add any common headers here
  },
});

export default instance;

How To Use Axios Instance in Components

Now that you have an Axios instance, you can easily use it in your React components. Import the instance and make requests:

// ExampleComponent.js
import React, { useEffect, useState } from 'react';
import axiosInstance from './axiosInstance'; // Adjust the path accordingly

const ExampleComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Using Axios instance to make a GET request
    axiosInstance.get('/endpoint')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      {data ? (
        <p>Data: {JSON.stringify(data)}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default ExampleComponent;

This example demonstrates a simple GET request using the Axios instance. You can send any type of request with this instance as you do before.

Conclusion

By following this guide, you'll be able to use Axios instances effectively in your React applications. With this approach, you can easily manage your HTTP request configuration in a centralized point.

Thank you for reading.