Skip to content

Instantly share code, notes, and snippets.

@aemc
Created February 22, 2021 15:53
Show Gist options
  • Select an option

  • Save aemc/4ac3b12e21b2b6a177d8b9be4a5a4891 to your computer and use it in GitHub Desktop.

Select an option

Save aemc/4ac3b12e21b2b6a177d8b9be4a5a4891 to your computer and use it in GitHub Desktop.

Revisions

  1. aemc revised this gist Feb 22, 2021. No changes.
  2. aemc created this gist Feb 22, 2021.
    47 changes: 47 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    import { Suspense, useState, useEffect } from 'react';

    const UserProfile = ({ profile }) => {
    return (
    <>
    <h1>{profile.name}</h1>
    <h2>{profile.email}</h2>
    </>
    );
    };
    const SuspensefulUserProfile = ({ profile }) => {
    return (
    <Suspense
    fallback={
    <div>
    <h1>Please wait ...</h1>
    </div>
    }>
    <UserProfile profile={profile} />
    </Suspense>
    );
    };
    const UserProfileList = ({ userProfileList }) => {
    return (
    <>
    {Object.entries(userProfileList).map([userId, profile] => (
    <SuspensefulUserProfile profile={profile} key={userId} />
    )}
    </>
    )
    };
    const App = () => {
    const [userProfileList, setUserProfileList] = useState({});
    const userIds = [1, 2, 3]; // could be fetch call to get user Ids but left as a hardcode array of userIds in this case
    useEffect(() => {
    userIds.map(userId => (
    fetchUserProfile(userId).then((profile) => setUserProfileList(prevData => { ...prevData, [userId]: profile }));
    )
    }, [userIds])
    return (
    <UserProfileList userProfileList={userProfileList} />
    )
    }

    1. The fallback prop is required in the Suspense component.
    2. Previous code was fetching before rendering. I've changed it to fetching and rendering at the same time.
    3. There's a race condition happening within SuspensefulUserProfile so I've moved it in the parent component and have its data passed down