A simple project demonstrating how to handle API calls in React using Axios.
├── 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
- 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
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" }
]cd backend
npm install
npm startServer runs on http://localhost:3000
cd frontend
npm install
npm run devReact app runs on http://localhost:5173
import axios from "axios";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);
}
})();
}, []);users- Stores fetched dataloading- Shows loading indicatorerror- Handles error states
server: {
proxy: {
'/api': 'http://localhost:3000'
}
}This proxies /api requests to the backend server, avoiding CORS issues.
- Frontend: React, Axios, Vite
- Backend: Express.js, Node.js