Skip to content

Instantly share code, notes, and snippets.

@FarooqAR
Last active January 12, 2021 07:34
Show Gist options
  • Save FarooqAR/552610d3e1a22e61c0fbb9f907774fa4 to your computer and use it in GitHub Desktop.
Save FarooqAR/552610d3e1a22e61c0fbb9f907774fa4 to your computer and use it in GitHub Desktop.

Three problems with this code:

  1. SuspensefulUserProfile is not correctly utilizing the Suspense. We need to fetch data as we render, instead of first rendering and then fetching (through useEffect).
  2. UserProfile component should be responsible for fetching the data instead of SuspensefulUserProfile.
  3. There is no fallback component. This will lead to a poor user experience.

Corrected:

import { Suspense, useState, useEffect } from 'react';

const SuspensefulUserProfile = ({ userId }) => {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <UserProfile userId={userId}/>
    </Suspense>
  );
};
const UserProfile = ({ userId }) => {
  // Assuming fetchUserProfile gives the correct output. Not exactly a promise. 
  const user = fetchUserProfile(userId);
  return (
    <>
      <h1>{user.name}</h1>
      <h2>{user.email}</h2>
    </>
  );
};
const UserProfileList = () => (
  <>
    <SuspensefulUserProfile userId={1} />
    <SuspensefulUserProfile userId={2} />
    <SuspensefulUserProfile userId={3} />
  </>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment