javascriptreactjsloading

How to display a fallback value while waiting for API data?


I'm building a dashboard in React, and I want to greet the user like "Hi, {firstName}!" But the data is fetched from an API, and sometimes it's not immediately available.

<h2 className="mb-4">Hi, {user?.firstName || '{name}'}!</h2>

I tried using optional chaining (user?.firstName) and fallback values (|| '{name}'), but I'm not sure if this is the best way. Is there a better or cleaner approach for this?


Solution

  • 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.