Axios
Axios in React
Axios in React simplifies HTTP requests using a promise-based API for methods like get, post, put, delete, and patch, offering features like automatic JSON transformation, request/response interception, cancellation, timeout settings, and built-in error handling (rejecting on 4xx/5xx status codes). Key properties include response.data for payload, error.response for detailed HTTP errors, config for settings (headers, timeouts), and axios.create() for custom instances, making API communication clean and efficient in React apps.
axios(config): The base method, takes a config object for any request type.axios.get(url, config): Fetches data from a URL.axios.post(url, data, config): Sends data to create a resource.axios.put(url, data, config): Updates an existing resource.axios.delete(url, config): Deletes a resource.axios.patch(url, data, config): Partially updates a resource.axios.head(url, config): Gets headers without response body.axios.options(url, config): Checks server options.
- Promises: Handles async operations with
.then()(success) and.catch()(error). - Automatic JSON: Converts JSON responses to JavaScript objects automatically.
- Interceptors: Modify requests or responses globally before handling (e.g., adding auth tokens).
- Error Handling: Throws errors for non-2xx status codes (404, 500), unlike Fetch.
- Timeouts: Set
timeoutin config to prevent hanging requests. - Cancellation: Cancel ongoing requests using
CancelTokenorAbortController. axios.create(): Creates reusable instances with default configs (base URL, headers).
import axios from 'axios';
import React, { useEffect, useState } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/items') // .get(url, { params: {} }) for query params
.then(response => {
setData(response.data); // Access data here
})
.catch(error => {
console.error('Error fetching data:', error); // Detailed error handling
});
}, []);
return (
<div>
{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : <p>Loading...</p>}
</div>
);
}
import axios from "axios";
import axios from "axios";is an ES6 JavaScript module statement to bring the Axios library into your project, allowing you to make HTTP requests (like GET, POST) for fetching or sending data to servers, commonly used in front-end frameworks (React, Vue) and Node.js after installing with npm install axios or yarn add axios.
- Imports the library: Makes all of Axios's functions (e.g.,
axios.get(),axios.post()) available in your file. - Enables API calls: Lets your web app communicate with APIs to get or send data.
- Uses Promises: Handles asynchronous operations with
.then()for success and.catch()for errors, or withasync/await.
// 1. Install first (in your terminal): npm install axios or yarn add axios
import axios from 'axios'; // 2. Import it
async function fetchUserData() {
try {
const response = await axios.get('https://api.example.com/users/1'); // 3. Make a GET request
console.log(response.data); // Log the data from the server
} catch (error) {
console.error('Error fetching data:', error); // Handle errors
}
}
fetchUserData();
- React/Vue: Import at the top of your component files.
- Node.js (CommonJS): Use
const axios = require('axios');. - Browser (CDN): Include
<script src="cdn.jsdelivr.net"></script>in your HTML