Created
February 22, 2021 15:53
-
-
Save aemc/4ac3b12e21b2b6a177d8b9be4a5a4891 to your computer and use it in GitHub Desktop.
Suspense
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment