I'm playing with React suspense example. Everything makes sense to me except I don't know how to hide a promise from executing.
export function fetchProfileData() {
let userPromise = fetchUser();
return {
user: wrapPromise(userPromise),
};
}
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;
}
}
};
}
In their example, whenever fetchProfileData
in invoked, the promise is launched, and since the status is pending initially, it raises to the suspense for the loader.
But now where do I put the root ProfileDetails
.
import { fetchProfileData } from "./fakeApi";
const resource = fetchProfileData();
function ProfilePage() {
return (
<Suspense
fallback={<h1>Loading profile...</h1>}
>
<ProfileDetails />
</Suspense>
);
}
Suppose i have an app, do I just do
function App() {
return <ProfilePage />
}
My question is, when is the promise executed in React? Right after I launch the page? If that's the case, how do I prevent it to be executed ex. if I'm not allowed to see that page. Do i do the following?
function App() {
if (notAllowed) return
return <ProfilePage />
}
Does this ever gonna work? I have serious doubt. Please help.
In the documentation it has this line, but i don't know what it means.
As a data fetching library author, you can enforce this by making it impossible to get a resource object without also starting a fetch. Every demo on this page using our “fake API” enforces this.