aboutreact axios

About React Axios

React Axios is a popular library that allows developers to make HTTP requests from their React applications. It is a promise-based library that provides an easy-to-use interface for performing asynchronous operations.

Installation

Before using React Axios, it must be installed in your project. This can be done using npm:

npm install axios

Usage

Once Axios is installed, it can be used in your React components by importing it:

import axios from 'axios';

You can then use the axios object to make HTTP requests:

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

The above code will make a GET request to the '/api/data' endpoint and log the response data to the console. If there is an error, it will log the error to the console.

Axios also supports other HTTP methods, including POST, PUT, and DELETE:

  • axios.post(url, data)
  • axios.put(url, data)
  • axios.delete(url)

Interceptors

Axios also provides interceptors that allow you to intercept requests or responses before they are handled by the application. This can be useful for adding headers, handling errors, and more.

To add an interceptor to Axios, you can use the following code:

axios.interceptors.request.use(config => {
  // Do something before the request is sent
  return config;
}, error => {
  // Do something with the request error
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
  // Do something with the response data
  return response;
}, error => {
  // Do something with the response error
  return Promise.reject(error);
});

The above code adds request and response interceptors to Axios. The request interceptor is called before the request is sent, and the response interceptor is called after the response is received. Both interceptors can modify the request or response before they are handled by the application.

Configuring defaults

Axios also allows you to configure defaults that will be applied to all requests made with Axios:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');

The above code sets a default base URL for all requests and adds an authorization header to all requests using a bearer token stored in local storage.

Overall, React Axios is a powerful library that provides an easy-to-use interface for making HTTP requests from React applications. With its support for interceptors and default configuration, it is a great tool for building robust web applications.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe