Created
August 21, 2021 10:37
-
-
Save Dchole/6972d23dd4522ae9a1cb2e75056b6fac to your computer and use it in GitHub Desktop.
React Suspense solution
This file contains 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
/** | |
* Core issues | |
* 1) The Suspense component has no fallback component | |
* 2) Fetching data with useEffect causes the component to render before fetching the data | |
* 3) Data was fetched outside the suspense. Data needs to be handled by Suspense it therefore should be fetched inside the Suspense | |
*/ | |
function getUserProfile(userId) { | |
return { | |
profile: wrapPromise(fetchUserProfile(userId)) | |
}; | |
} | |
const SuspensefulUserProfile = ({ userId }) => { | |
const userProfile = getUserProfile(userId); | |
return ( | |
<Suspense fallback={<p>Loading..</p>}> | |
<UserProfile userProfile={userProfile} /> | |
</Suspense> | |
); | |
}; | |
const UserProfile = ({ userProfile }) => { | |
const data = userProfile.profile.read(); | |
return ( | |
<> | |
<h1>{data.name}</h1> | |
<h2>{data.email}</h2> | |
</> | |
); | |
}; | |
const UserProfileList = () => ( | |
<> | |
<SuspensefulUserProfile userId={1} /> | |
<SuspensefulUserProfile userId={2} /> | |
<SuspensefulUserProfile userId={3} /> | |
</> | |
); | |
// live code example at https://codesandbox.io/s/festive-sanderson-6kplg?file=/src/TestComponent.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment