Hey everyone, I'm working on a new project that involves fetching data from a REST API and displaying it in a React frontend. I'm using `axios` for the requests, but I'm running into some issues with handling asynchronous operations and displaying loading states correctly.
Specifically, I'm trying to implement a pattern where I fetch data on component mount, show a "Loading..." message, and then render the data once the request is successful. If there's an error, I want to display an error message.
Here's a simplified version of what I have so far:
// Example Component
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUser = async () => {
try {
setLoading(true);
const response = await axios.get(`/api/users/${userId}`);
setUser(response.data);
setError(null);
} catch (err) {
setError('Failed to fetch user data.');
setUser(null);
} finally {
setLoading(false);
}
};
fetchUser();
}, [userId]);
if (loading) {
return Loading user profile...;
}
if (error) {
return Error: {error};
}
if (!user) {
return No user data available.;
}
return (
{user.name}
Email: {user.email}
Member Since: {new Date(user.joinedDate).toLocaleDateString()}
);
}
export default UserProfile;
I'm wondering if there are more efficient or cleaner ways to handle this common pattern. Any advice on error boundaries, data fetching libraries, or best practices for API interaction in the frontend would be greatly appreciated!