Skip to content

Instantly share code, notes, and snippets.

@Dchole
Created August 21, 2021 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dchole/6972d23dd4522ae9a1cb2e75056b6fac to your computer and use it in GitHub Desktop.
Save Dchole/6972d23dd4522ae9a1cb2e75056b6fac to your computer and use it in GitHub Desktop.
React Suspense solution
/**
* 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