Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support async render function in getDataFromTree / getMarkupFromTree #6576

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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