0

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?

1
  • What you've got looks fine. An alternative would be initialising the user state with placeholder values, eg const [user, setUser] = useState({firstName: '{name}'}) Commented Jun 1 at 23:55

3 Answers 3

1

React has two handy features, the use hook/api and the <Suspense> component.

The use hook/api, introduced in React 19, lets you suspend the component you are using it in while it is waiting for the resource prop you pass to it. The <Suspense> component lets you display a fallback, through its fallback prop, while its children are loading. You can use these two together to display a fallback value while you are fetching the data.

Like so:

import { use, Suspense } from "react";

const Greeting = ({ promise }) => {
  const user = use(promise);
  
  return <h2 className="mb-4">Hi, {user.firstName}!</h2>;
};

const Dashboard = () => {
  return (
    <Suspense fallback={<h2>Example: Loading Dashboard</h2>}>
      <Greeting promise={YOUR_DATA_PROMISE} />
    </Suspense>
  );
};

export default Dashboard;

Please do look at the documentation:

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

i think this is the quick approach you can take and show Loading... text of the basis of api response there are multiple way to handle this case its up to you

{user ? (
      <h2 className="mb-4">Hi, {user.firstName}!</h2>
    ) : (
      <h2 className="mb-4">Loading...</h2>
    )}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.