React SSR Suspense fallback & streaming suport : Example Code
Created: 1 Sep 2022,Updated: 1 Sep 2022,(0) fork,(0) stars,(0) comments,
// file: react_test.ts
// it just for my note
import React from "https://esm.sh/react@18.2.0";
import ReactDomServer from "https://esm.sh/react-dom@18.2.0/server";
import { Handler, serve } from "https://deno.land/std@0.161.0/http/server.ts";
const Module = {
default: () =>
React.createElement("div", {
hello: "World",
}, "Dynamic Modules"),
};
const DynComp = React.lazy(async () => {
await new Promise((resolve) => {
setTimeout(() => {
resolve(1);
}, 5000);
});
return Module;
});
const Component = (props: { hello?: string }) => {
return React.createElement("div", {}, [
React.createElement("h3", {}, props?.hello ?? "Hello React"),
React.createElement(React.Suspense, {
fallback: React.createElement("span", {}, "Loading..."),
}, [
React.createElement(DynComp),
]),
React.createElement("p", {}, "I am here"),
]);
};
//await stream.allReady
const ac = new AbortController();
const handler: Handler = async (req) => {
const stream = await ReactDomServer.renderToReadableStream(
React.createElement(Component, { hello: "Hello World" }),
{ signal: ac.signal },
);
return new Response(stream, {
headers: {
"content-type": "text/html; charset=utf-8",
},
});
};
await serve(handler, { port: 3000, signal: ac.signal });