This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
/
getDataFromTree.ts
54 lines (48 loc) · 1.82 KB
/
getDataFromTree.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React from 'react';
import { getApolloContext, RenderPromises } from '@apollo/react-common';
export function getDataFromTree(
tree: React.ReactNode,
context: { [key: string]: any } = {}
) {
return getMarkupFromTree({
tree,
context,
// If you need to configure this renderFunction, call getMarkupFromTree
// directly instead of getDataFromTree.
renderFunction: require('react-dom/server').renderToStaticMarkup
});
}
export type GetMarkupFromTreeOptions = {
tree: React.ReactNode;
context?: { [key: string]: any };
renderFunction?: (tree: React.ReactElement<any>) => string;
};
export function getMarkupFromTree({
tree,
context = {},
// The rendering function is configurable! We use renderToStaticMarkup as
// the default, because it's a little less expensive than renderToString,
// and legacy usage of getDataFromTree ignores the return value anyway.
renderFunction = require('react-dom/server').renderToStaticMarkup
}: GetMarkupFromTreeOptions): Promise<string> {
const renderPromises = new RenderPromises();
function process(): Promise<string> | string {
// Always re-render from the rootElement, even though it might seem
// better to render the children of the component responsible for the
// promise, because it is not possible to reconstruct the full context
// of the original rendering (including all unknown context provider
// elements) for a subtree of the original component tree.
const ApolloContext = getApolloContext();
const html = renderFunction(
React.createElement(
ApolloContext.Provider,
{ value: { ...context, renderPromises } },
tree
)
);
return renderPromises.hasPromises()
? renderPromises.consumeAndAwaitPromises().then(process)
: html;
}
return Promise.resolve().then(process);
}