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

feat(gatsby): enable async rendering with react 18 #32188

Merged
merged 14 commits into from
Jul 2, 2021
35 changes: 35 additions & 0 deletions packages/gatsby/cache-dir/server-utils/writable-as-promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Writable } from "stream"

export class WritableAsPromise extends Writable {
constructor() {
super()

this._output = ``
this._deferred = {
promise: null,
resolve: null,
reject: null,
}
this._deferred.promise = new Promise((resolve, reject) => {
this._deferred.resolve = resolve
this._deferred.reject = reject
})
}

_write(chunk, enc, cb) {
this._output += chunk.toString()

cb()
}

end() {
this._deferred.resolve(this._output)

this.destroy()
}

// disguise us as a promise
then(resolve, reject) {
return this._deferred.promise.then(resolve, reject)
}
}
28 changes: 26 additions & 2 deletions packages/gatsby/cache-dir/static-entry.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const React = require(`react`)
const path = require(`path`)
const { renderToString, renderToStaticMarkup } = require(`react-dom/server`)
const {
renderToString,
renderToStaticMarkup,
pipeToNodeWritable,
} = require(`react-dom/server`)
const { ServerLocation, Router, isRedirect } = require(`@gatsbyjs/reach-router`)
const { merge, flattenDeep, replace } = require(`lodash`)
const { StaticQueryContext } = require(`gatsby`)
Expand Down Expand Up @@ -260,7 +264,27 @@ export default async function staticPage({
// If no one stepped up, we'll handle it.
if (!bodyHtml) {
try {
bodyHtml = renderToString(bodyComponent)
// react 18 enabled
if (pipeToNodeWritable) {
const {
WritableAsPromise,
} = require(`./server-utils/writable-as-promise`)
const writableStream = new WritableAsPromise()
const { startWriting } = pipeToNodeWritable(
bodyComponent,
writableStream,
{
onCompleteAll() {
startWriting()
},
onError() {},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to ignore errors here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we won't do streaming yet until libs have adopted and maybe we never do.
React still throws the error so this is just to don't show the warning.

}
)

bodyHtml = await writableStream
} else {
bodyHtml = renderToString(bodyComponent)
}
} catch (e) {
// ignore @reach/router redirect errors
if (!isRedirect(e)) throw e
Expand Down