Axios is a JavaScript library used to send HTTP requests from the frontend to the backend and communicate with APIs.
We commonly use Axios to:
- GET – Fetch data from an API.
- POST – Send new data to an API.
- PUT – Update existing data.
- DELETE – Delete data from an API.
- How to install Axios :
Open your VS Code terminal:
npm install axios
- Axios GET example:
Let's fetch user data from an API.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [users, setUsers] = useState([]); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/users') .then((response) => { setUsers(response.data); }) .catch((error) => { console.log(error); }); }, []); return ( <div> <h1>User Details</h1> {users.map((user) => ( <p key={user.id}>{user.name}</p> ))} </div> ); }
export default App;
Explanation:
- useEffect() – Runs the API request after the component mounts.
- axios.get() – Fetches data from the API.
- then() – Handles successful responses.
- response.data – Contains the API response data.
- catch() – Handles errors.
- setUsers() – Stores the fetched data in state.
- Four Axios methods:
Method Purpose
GET Read data
POST Create data
PUT Update data
DELETE Delete data
