import React, { useEffect, useState } from 'react';
export default function Dashboard() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/user')
.then((res) => res.json())
.then((data) => {
setUser(data);
setLoading(false);
});
}, []);
return (
<h2>
Hi, {loading ? 'loading...' : user.firstName}!
</h2>
);
}
You can also use a ternary to conditionally render based on data availability:
{user ? (
<h2>Hi, {user.firstName}!</h2>
) : (
<h2>Hi, loading...</h2>
)}
I’ve faced this challenge before when building dashboards that rely on asynchronous API data. Finding a balance between clean code and good user experience is key. From my experience, managing explicit loading states and using the nullish coalescing operator (??) often leads to the most reliable and readable solution.
I hope my answer helps you.
I learned a lot from you. Thank you.