Fetching Data with Fetch and Axios
Using the Fetch API
The fetch
API is a built-in JavaScript method used to make HTTP requests.
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setUsers(data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Using Axios
Axios is a third-party library that simplifies HTTP requests and offers better error handling than fetch
.
npm install axios
import axios from 'axios';
import { useEffect, useState } from 'react';
function UsersWithAxios() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
setUsers(response.data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Handling Loading and Error States
Always handle loading and error states to improve user experience and make your app more reliable.
- Use conditional rendering to display loading spinners or skeletons.
- Show friendly error messages when a request fails.
- Keep the UI responsive and informative at all times.
Using React Query for Server State Management
React Query (also known as @tanstack/react-query
) is a powerful library for managing server-side state and
fetching, caching, and updating data in React applications.
Installation
npm install @tanstack/react-query
Setup
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourComponent />
</QueryClientProvider>
);
}
Fetching Data with useQuery
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
function UsersWithReactQuery() {
const { data, isLoading, error } = useQuery({
queryKey: ['users'],
queryFn: () => axios.get('https://jsonplaceholder.typicode.com/users').then(res => res.data)
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Benefits of React Query
- Automatic caching and background refetching
- Pagination and infinite scrolling support
- Retry failed requests automatically
- Simplified loading and error handling
Conclusion
Data fetching is a fundamental part of building dynamic React applications.
While fetch
and axios
are great for simple needs,
React Query offers a powerful solution for handling complex server state.
In the next post, we’ll focus on performance optimization in React using techniques like memoization and lazy loading.
0 Comments