React Hooks: how to wait for the data to be fetched before rendering

Just don’t render it when the data is undefined:

export const CardDetails = () => {
  const [card, setCard] = useState();

  const { id } = useParams();

  useEffect(() => {
    fetch(`http://localhost:3001/cards/${id}`)
      .then((res) => res.json())
      .then((data) => setCard(data));
  }, [id]);

  if (card === undefined) {
    return <>Still loading...</>;
  }

  return <DetailsRow data={card} />;
};

Leave a Comment