You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a usecase where I have an SPA that cannot currently be rendered on the server, but I still want to load route data and inject it into the HTML shell. Right now I was able to extract the required logic from lib/dom/server.tsx but it would be better not to rely on internal implementations. Something like loadHydrationData(request, routes).
import { createStaticHandler, isRouteErrorResponse, StaticHandlerContext } from "react-router";
const ESCAPE_LOOKUP: { [match: string]: string } = {
// impl
};
const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
let htmlEscape = (str: string) =>
str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
let serializeErrors = (
errors: StaticHandlerContext["errors"]
): StaticHandlerContext["errors"] => {
// impl
}
export let loadHydrationData = async (req: Request, routes: RouteObject[]): Response | string => {
let { query } = createStaticHandler(routes);
let context = await query(req);
if (context instanceof Response) {
return context;
}
let data = {
loaderData: context.loaderData,
actionData: context.actionData,
errors: serializeErrors(context.errors),
};
let json = htmlEscape(JSON.stringify(JSON.stringify(data)));
return `<script>window.__staticRouterHydrationData = JSON.parse(${json});</script>`;
}
The implementation is quite simple and would just require a small refactor + export.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have a usecase where I have an SPA that cannot currently be rendered on the server, but I still want to load route data and inject it into the HTML shell. Right now I was able to extract the required logic from
lib/dom/server.tsx
but it would be better not to rely on internal implementations. Something likeloadHydrationData(request, routes)
.The implementation is quite simple and would just require a small refactor + export.
Beta Was this translation helpful? Give feedback.
All reactions