Skip to content

Instantly share code, notes, and snippets.

@da7a90
Created September 20, 2021 22:49
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 da7a90/f773327a489c23e1631609f46649beb1 to your computer and use it in GitHub Desktop.
Save da7a90/f773327a489c23e1631609f46649beb1 to your computer and use it in GitHub Desktop.
/**
* 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