Ads

Ad

Master React Axios in Hindi | Beginner to Pro API Handling Guide

Master React Axios in Hindi

React Axios Introduction

React ek popular front-end library hai jo modern web applications banane ke liye use hoti hai. Jab bhi hum React se koi real-world app banate hain, toh hume backend server se data fetch (lana) ya data send (bhejna) padta hai.

Iss purpose ke liye do popular options hote hain:

  • Fetch API (browser ka built-in method)
  • Axios (third-party library)

Fetch API simple hai, lekin Axios usse zyada powerful aur easy syntax provide karta hai. Isliye developers mostly Axios prefer karte hain.

🔹 Axios ke Uses kya hai?

Axios ek promise-based HTTP client hai jo browser aur Node.js dono environment me kaam karta hai.

✨ Features / Uses of Axios:

  • Simple aur readable syntax
  • Request aur Response interceptors (data modify karne ke liye)
  • Automatic JSON data transform
  • Easy error handling
  • Cancel request karne ki facility
  • Timeout aur retry option

🔹 Axios kaha use hota hai?

  • Data Fetch karne ke liye: API se users, posts, products etc. laane ke liye
  • Data Send karne ke liye: Form data ya login info server pe bhejne ke liye
  • Authentication: Token har request ke sath bhejna
  • Real-time apps: Jahan fast aur multiple API requests hoti hain

🔹 Axios kyun aaya hai (Why Axios over Fetch)?

Fetch API Problem Axios Advantage
Long syntax Short aur readable code
JSON manually parse karna padta hai Automatic JSON parsing
Error handling limited Detailed error response
Cancel request tough Cancel request easy

🔹 How to Use Axios in React?

Step 1: Install Axios

npm install axios

Step 2: Simple GET Request


import React, { useEffect, useState } from "react";
import axios from "axios";

function Users() {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/users")
            .then(res => setUsers(res.data))
            .catch(err => console.error("Error:", err));
    }, []);

    return (
        

Users List

    {users.map(u =>
  • {u.name}
  • )}
); } export default Users;

👉 yaha axios.get() se data fetch hua aur setUsers me store ho gaya.

Step 3: POST Request


import React, { useState } from "react";
import axios from "axios";

function CreateUser () {
    const [name, setName] = useState("");

    const handleSubmit = () => {
        axios.post("https://jsonplaceholder.typicode.com/users", { name })
            .then(res => console.log("User  Created:", res.data))
            .catch(err => console.error("Error:", err));
    };

    return (
        
setName(e.target.value)} />
); } export default CreateUser ;

👉 Axios automatically data ko JSON me convert kar deta hai.

Step 4: PUT aur DELETE


// Update User (PUT)
axios.put("https://jsonplaceholder.typicode.com/users/1", {
    name: "Updated Name"
});

// Delete User
axios.delete("https://jsonplaceholder.typicode.com/users/1");

Step 5: Async/Await Syntax


import React, { useEffect, useState } from "react";
import axios from "axios";

function Posts() {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        const fetchPosts = async () => {
            try {
                let res = await axios.get("https://jsonplaceholder.typicode.com/posts");
                setPosts(res.data);
            } catch (err) {
                console.error("Error:", err);
            }
        };
        fetchPosts();
    }, []);

    return (
        

Posts

{posts.map(p =>

{p.title}

)}
); } export default Posts;

👉 Code jyada clean aur readable ho jata hai.

🔹 Advanced Axios Use

Axios Instance


// src/api/axiosInstance.js
import axios from "axios";

const api = axios.create({
    baseURL: "https://jsonplaceholder.typicode.com",
    timeout: 5000,
    headers: { "Content-Type": "application/json" }
});

export default api;

Use:


import api from "./api/axiosInstance";

api.get("/users").then(res => console.log(res.data));

Interceptors


import api from "./api/axiosInstance";

// Request Interceptor
api.interceptors.request.use(config => {
    config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
    return config;
});

// Response Interceptor
api.interceptors.response.use(
    res => res,
    err => {
        if (err.response.status === 401) {
            console.error("Unauthorized! Please login.");
        }
        return Promise.reject(err);
    }
);

Cancel Request


import axios from "axios";
const controller = new AbortController();

axios.get("https://jsonplaceholder.typicode.com/posts", {
    signal: controller.signal
});

// Cancel request
controller.abort();

🔹 Real Example – Todo App


import React, { useEffect, useState } from "react";
import api from "./api/axiosInstance";

function TodoApp() {
    const [todos, setTodos] = useState([]);

    useEffect(() => {
        const fetchTodos = async () => {
            let res = await api.get("/todos");
            setTodos(res.data.slice(0, 10));
        };
        fetchTodos();
    }, []);

    return (
        

Todo List

{todos.map(todo => (

✅ {todo.title} - {todo.completed ? "Done" : "Pending"}

))}
); } export default TodoApp;

🔹 Conclusion

👉 Axios ek powerful library hai jo React me API handling ko easy banata hai.

Beginners ke liye: GET, POST, PUT, DELETE requests simple hain.

Advanced developers ke liye: Interceptors, cancel requests, aur Axios instances helpful hote hain.

Agar aap real-world scalable React apps bana rahe ho, toh Axios use karna ek smart choice hai.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!