Skip to content

Instantly share code, notes, and snippets.

@sseletskyy
Created December 12, 2021 19:19
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 sseletskyy/bc5d7641d24eeb30680b2404af78c214 to your computer and use it in GitHub Desktop.
Save sseletskyy/bc5d7641d24eeb30680b2404af78c214 to your computer and use it in GitHub Desktop.
react-suspense-api-example.jsx
/**
* First issue I see is the way how useEffect is defined
* The dependency list should not contain `setData`, but only `userId`
*
* The second issue is that there is no need to use `useEffect`
* in case the React component is using Suspense API
* So we can get rid of `useEffect` and `useState` as well.
* Instead we should call `fetchUserProfile` and pass the result to the child component.
* And also we can define `fallback` prop
*
*
* const SuspensefulUserProfile = ({ userId }) => {
* const data = fetchUserProfile(userId);
* return (
* <Suspense fallback={<h3>...loading</h3>}>
* <UserProfile data={data} />
* </Suspense>
* );
* };
*
*
* The third issue is in the nested component `UserProfile`
* According to Suspense API variable `data` has a method `read` which
* will return expected data when fetch request (the promise) is resolved.
* So `UserProfile` should look like this
*
* const UserProfile = ({ data }) => {
* const { name, email } = data.read();
* return (
* <>
* <h1>{name}</h1>
* <h2>{email}</h2>
* </>
* );
* };
*
*
*/
import { Suspense } from 'react';
const SuspensefulUserProfile = ({ userId }) => {
const data = fetchUserProfile(userId);
return (
<Suspense fallback={<h3>...loading</h3>}>
<UserProfile data={data} />
</Suspense>
);
};
const UserProfile = ({ data }) => {
const { name, email } = data.read();
return (
<>
<h1>{name}</h1>
<h2>{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