Skip to content

Instantly share code, notes, and snippets.

@AmanAgarwal041
Created October 1, 2021 08:23
Show Gist options
  • Save AmanAgarwal041/c873de47c1f19a89ae9a55f66b60f96e to your computer and use it in GitHub Desktop.
Save AmanAgarwal041/c873de47c1f19a89ae9a55f66b60f96e to your computer and use it in GitHub Desktop.
/**
* There were 3 violations to use Suspense in concurrent mode
*
* 1. Suspended Components should have a pending state for the suspensions to work
* 2. We need to wrap api to a promisified function which provides states with pending promises or resolved data, so that we can read the states inside the components
* 3. We don't need to have a state or useEffect to read the data in the suspended component
*
***/
import { Suspense } from 'react';
const fetchUser = (userId) => {
return wrapPromise(fetchUserProfile(userId))
}
function wrapPromise(promise) {
let status = "pending";
let result;
let suspender = promise.then(
(r) => {
status = "success";
result = r;
},
(e) => {
status = "error";
result = e;
}
);
return {
read() {
if (status === "pending") {
throw suspender;
} else if (status === "error") {
throw result;
} else if (status === "success") {
return result;
}
}
};
}
const SuspensefulUserProfile = ({ userId }) => {
return (
<Suspense fallback={'Loading'}>
<UserProfile resource={fetchUser(userId)} />
</Suspense>
);
};
const UserProfile = ({ resource }) => {
const data = resource.read()
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