@react-hook/server-promises
Version:
A React hook for continuously rendering a React tree until no promises are pushed to server-promises's context in a given render.
37 lines (30 loc) • 1.26 kB
JavaScript
import * as React from 'react';
const __reactCreateElement__ = React.createElement;
export const ServerPromisesContext = /*#__PURE__*/React.createContext( /*#__PURE__*/createPromisesCache());
export const useServerPromises = () => React.useContext(ServerPromisesContext); // renders the app until there are no promises that get pushed to the cache array
export function loadPromises(tree, // eslint-disable-next-line @typescript-eslint/no-var-requires
render = require('react-dom/server').renderToStaticMarkup) {
const cache = createPromisesCache();
const process = () => {
const html = render(__reactCreateElement__(ServerPromisesContext.Provider, {
value: cache,
children: tree
}));
return cache.promises.length > 0 ? cache.load().then(process) : html;
};
return Promise.resolve().then(process);
} // preloads all of the async components used in the current react tree
function createPromisesCache(initial = []) {
function _ref() {
return cache.promises = [];
}
const cache = {
// Map from Query component instances to pending promises.
promises: initial,
push: (...args) => cache.promises.push(...args),
load() {
return Promise.all(cache.promises).then(_ref);
}
};
return cache;
}