Skip to content

gourabofficial/APIs-Handling-In-React

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

API Handling in React

A simple project demonstrating how to handle API calls in React using Axios.

Project Structure

├── backend/          # Express.js API server
│   ├── app.js       # Main server file
│   └── package.json
└── frontend/        # React application
    ├── src/
    │   └── App.jsx  # Main component with API handling
    └── package.json

Features

  • Backend API - Express.js server with endpoints
  • Frontend - React app consuming the API
  • Error Handling - Proper error states
  • Loading States - Loading indicators during data fetch
  • Search Filtering - Query parameter support for filtering users by role
  • Delayed Response - 3-second timeout to simulate network delay

API Endpoints

GET /api/data

Returns a list of users with a 3-second delay.

Query Parameters:

  • search - Filter users by role (e.g., ?search=admin)

Response:

[
  { "id": 1, "name": "Alice", "email": "alice@example.com", "role": "admin" },
  { "id": 2, "name": "Bob", "email": "bob@example.com", "role": "user" }
]

Setup & Installation

Backend

cd backend
npm install
npm start

Server runs on http://localhost:3000

Frontend

cd frontend
npm install
npm run dev

React app runs on http://localhost:5173

How API Handling Works

1. Axios Setup

import axios from "axios";

2. API Call with useEffect

useEffect(() => {
  (async () => {
    try {
      setError(false);
      setLoading(true);
      const response = await axios.get("/api/data");
      console.log(response.data);
      setUsers(response.data);
      setLoading(false);
    } catch (error) {
      setError(true);
      setLoading(false);
    }
  })();
}, []);

3. State Management

  • users - Stores fetched data
  • loading - Shows loading indicator
  • error - Handles error states

4. Vite Proxy Configuration

server: {
  proxy: {
    '/api': 'http://localhost:3000'
  }
}

This proxies /api requests to the backend server, avoiding CORS issues.

Technologies Used

  • Frontend: React, Axios, Vite
  • Backend: Express.js, Node.js

About

API Handling LIke a Pro In React js .

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published