React useAsync for SSR
npm install useasync-ssrReactDOM.renderToString called, AsyncManager saves promises that requested in react tree. Then when asyncManager.load called, await all promises resolved or rejected. Next render, AsyncManager will fill async values. Then you can get filled html.
tsx
import { Helmet } from "react-helmet";
import { useAsync } from "useasync-ssr";
function getCount() {
return fetch(API_URI + '/count').then(response => response.text()).then(v => parseInt(v));
}
export const Count1 = () => {
const count = useAsync(() => getCount());
return (
{'Count ' + count.value}
Count
Count: {count.value}
)
};
`
`tsx
const app = express();
app.get('/render', async (req, res) => {
const asyncManager = new AsyncManager();
const Tree = (
);
// Scan tree
ReactDOM.renderToString(Tree);
Helmet.renderStatic();
// Load async requests & save caches
const caches = await asyncManager.load();
// Filled content
const content = ReactDOM.renderToString(Tree);
// Make html with useAsync caches
const html = ;
// Send!
res.status(200);
res.send(\n${ReactDOM.renderToString(html)});
res.end();
});
``