@rest-hooks/ssr v0.7.11
Rest Hooks Server Side Rendering helpers
Hydrate/dehydration utilities for Rest Hooks
Server side
import express from 'express';
import { renderToPipeableStream } from 'react-dom/server';
import { createPersistedCacheProvder } from '@rest-hooks/ssr';
const app = express();
app.get('/*', (req: any, res: any) => {
const [ServerCacheProvider, controller] = createPersistedCacheProvder();
controller.fetch(NeededForPage, { id: 5 });
const { pipe, abort } = renderToPipeableStream(
<Document assets={assets}>
<ServerCacheProvider>{children}</ServerCacheProvider>
</Document>,
{
onCompleteShell() {
// If something errored before we started streaming, we set the error code appropriately.
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-type', 'text/html');
pipe(res);
},
onError(x: any) {
didError = true;
console.error(x);
res.statusCode = 500;
pipe(res);
},
},
);
// Abandon and switch to client rendering if enough time passes.
// Try lowering this to see the client recover.
setTimeout(abort, 1000);
});
app.listen(3000, () => {
console.log(`Listening at ${PORT}...`);
});
Client
import { hydrateRoot } from 'react-dom';
import { getDatafromDOM } from '@rest-hooks/ssr';
const data = getDatafromDOM();
hydrateRoot(
document,
<Document assets={assets}>
<CacheProvider initialState={data}>
{children}
<ServerDataComponent data={data} />
</CacheProvider>
</Document>,
);
API
createPersistedStore(managers) => ServerCacheProvider, controller
Used to server side render cache. Renders <ServerDataComponent/> inside to serialize cache so client can hydrate.
ServerDataComponent
Hydrate/dehydrates Rest Hooks cache. Contents are a script with JSON encoding of cache state sent from server.
getDatafromDOM()
Loads data from ServerDataComponent to initialize cache.
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago