Fetching Data from APIs in React
๐ Fetching Data from APIs in React
In a React app, you often need to get data from a web API to display things like user profiles, posts, weather info, etc.
๐ง Common Tools for Fetching Data
You can fetch API data using:
✅ Native JavaScript fetch()
✅ axios (popular third-party library)
✅ React Query, SWR (advanced options for caching, auto-refresh)
✅ Basic Example Using fetch()
Step 1: Use useEffect to call the API
jsx
Copy
Edit
import React, { useState, useEffect } from 'react';
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then((res) => res.json())
.then((data) => {
setUsers(data);
setLoading(false);
})
.catch((error) => {
console.error('Error fetching users:', error);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default Users;
๐ Example Using axios
First, install axios:
bash
Copy
Edit
npm install axios
Then use it:
jsx
Copy
Edit
import axios from 'axios';
import React, { useEffect, useState } from 'react';
function Posts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => setPosts(response.data))
.catch((error) => console.error('API error:', error));
}, []);
return (
<div>
<h2>Posts</h2>
{posts.slice(0, 5).map((post) => (
<p key={post.id}>{post.title}</p>
))}
</div>
);
}
๐ Optional: Handling Loading & Error States
Always show feedback to the user:
jsx
Copy
Edit
if (loading) return <p>Loading data...</p>;
if (error) return <p>Something went wrong!</p>;
๐ฆ Advanced Option: React Query (TanStack Query)
React Query handles caching, re-fetching, and more.
bash
Copy
Edit
npm install @tanstack/react-query
Example:
jsx
Copy
Edit
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
function Products() {
const { data, isLoading, error } = useQuery({
queryKey: ['products'],
queryFn: () => axios.get('/api/products').then(res => res.data)
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error loading products</p>;
return (
<ul>
{data.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
);
}
๐ก️ Best Practices
Tip Why
Use useEffect only for side effects Prevents multiple API calls
Always handle loading and error states Improves UX
Don’t hardcode URLs Use environment variables for production
Avoid unnecessary API calls Use caching or conditional fetching
Consider pagination Prevents overloading the UI with too much data
✅ Summary
To fetch data in React:
Use useEffect + fetch() or axios
Store the result in useState
Handle loading and error states
Display the data once it's ready
Learn React JS Course in Hyderabad
Read More
๐ API Integration & Data Fetching
Scroll Restoration in Single Page Apps
Private Routes and Authentication Flow
Handling 404 Pages with React Router
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment