How to defer based on a boolean value instead of a promise? #11755
-
Currently, I am trying to do cookie validation, and I want to use defer to wait until my frontend receives the cookie from my backend. Here is my code for the element: export function dashboardLoader() {
return defer({
hasSessionCookies: checkSessionCookies(),
});
}
export const Dashboard = () => {
const sessionCookie = useLoaderData() as {
hasSessionCookies?: boolean;
};
return (
<div>
<React.Suspense fallback={<p>Loading session cookie...</p>}>
<Await
resolve={sessionCookie.hasSessionCookies}
errorElement={<p>Error loading session cookie!</p>}
>
{(sessionCookie) => (
<p>
You have a session cookie which is{" "}
{sessionCookie.hasSessionCookies ? "true" : "false"}
</p>
)}
</Await>
</React.Suspense>
</div>
);
}; For my cookie logic (which I have manually tested) is this: export function getCookie(name: string): string | null {
const nameLenPlus = name.length + 1;
return (
document.cookie
.split(";")
.map((c) => c.trim())
.filter((cookie) => {
return cookie.substring(0, nameLenPlus) === `${name}=`;
})
.map((cookie) => {
return decodeURIComponent(cookie.substring(nameLenPlus));
})[0] || null
);
}
export function checkSessionCookies(): Promise<boolean> {
return Promise.resolve(getCookie(<name of cookie>) != null);
} In my router it looks like this: createBrowserRouter(
createRoutesFromElements(
.....
<Route
path="dashboard"
element={<Dashboard />}
loader={dashboardLoader}
/>
.....
)) I am not sure what the issue could be. If I inspect the page, the cookie shows up. The issue is hasSessionCookies keeps on being false as that is what keeps on being displayed. Any help would appreciated and thank you in advance |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Nevermind, I figured out the issue {(sessionCookie) => (...)} sessionCookie is just the hasSessionCookies value. Just a follow up question, is there a way to wait for a value to be true instead of awaiting the promise? function waitForSessionCookie() {
const poll = (resolve: any) => {
if (checkSessionCookies()) resolve();
else setTimeout((_: any) => poll(resolve), 400);
};
return new Promise(poll);
} and replaced
with
but it kept on showing the error page. Edit fixed my code:
It works. If there is a better or cleaner way to do this, please let me know. |
Beta Was this translation helpful? Give feedback.
Nevermind, I figured out the issue {(sessionCookie) => (...)} sessionCookie is just the hasSessionCookies value.
Just a follow up question, is there a way to wait for a value to be true instead of awaiting the promise?
EDIT: I tried implementing a timed await function: (credit to this stackoverflow post)
and replaced
with
but it kept on showing the error page.
…