Skip to content

Commit

Permalink
Support async options.renderFunction for getMarkupFromTree (apollogra…
Browse files Browse the repository at this point in the history
  • Loading branch information
richardscarrott authored and jimrandomh committed Jul 22, 2020
1 parent e80835f commit bd965df
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
- Make the `client` field of the `MutationResult` type non-optional, since it is always provided. <br/>
[@glasser](https://github.com/glasser) in [#6617](https://github.com/apollographql/apollo-client/pull/6617)

- Allow passing an asynchronous `options.renderFunction` to `getMarkupFromTree`. <br/>
[@richardscarrott](https://github.com/richardscarrott) in [#6576](https://github.com/apollographql/apollo-client/pull/6576)

## Apollo Client 3.0.2

## Bug Fixes
Expand Down
28 changes: 16 additions & 12 deletions src/react/ssr/getDataFromTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ export function getDataFromTree(
export type GetMarkupFromTreeOptions = {
tree: React.ReactNode;
context?: { [key: string]: any };
renderFunction?: (tree: React.ReactElement<any>) => string;
renderFunction?: (
tree: React.ReactElement<any>,
) => string | PromiseLike<string>;
};

export function getMarkupFromTree({
Expand All @@ -31,24 +33,26 @@ export function getMarkupFromTree({
}: GetMarkupFromTreeOptions): Promise<string> {
const renderPromises = new RenderPromises();

function process(): Promise<string> | string {
function process(): Promise<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 new Promise<string>(resolve => {
const element = React.createElement(
ApolloContext.Provider,
{ value: { ...context, renderPromises }},
tree,
);
resolve(renderFunction(element));
}).then(html => {
return renderPromises.hasPromises()
? renderPromises.consumeAndAwaitPromises().then(process)
: html;
});
}

return Promise.resolve().then(process);
Expand Down

0 comments on commit bd965df

Please sign in to comment.