Created
September 20, 2021 22:49
-
-
Save da7a90/f773327a489c23e1631609f46649beb1 to your computer and use it in GitHub Desktop.
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
/** | |
* Sid Barrack | |
* | |
* the issues identified are commented below with the correct implementation | |
*/ | |
import { Suspense, useState, useEffect } from 'react'; | |
/* | |
data needs to be outside of the component, because once the promise resolves(see comment on data loading component below), | |
suspense is going to try to render the component again and data must be synchronously available | |
*/ | |
let data; | |
/* | |
Suspense needs to be outside of the component that is doing the data loading. | |
It also has to be provided with the required fallback option | |
*/ | |
const SuspensefulUserProfile = () => { | |
return ( | |
<Suspense fallback={<div>Loading...</div>}> | |
<DataLoader /> | |
</Suspense> | |
); | |
} | |
/* | |
and in the data loading component, you need to throw a promise | |
in order to tell suspense that loading is in progress | |
*/ | |
const DataLoader = () => { | |
if (!data) { | |
throw fetchUserProfile(userId) | |
.then((profile) => { data = profile }); | |
} | |
return <UserProfile data={data} /> | |
} | |
const UserProfile = ({ data }) => { | |
return ( | |
<> | |
<h1>{data.name}</h1> | |
<h2>{data.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