From 9093cdfcf52cbc5297b9b678073636103dfecb3f Mon Sep 17 00:00:00 2001 From: Daniel Spitzer Date: Tue, 13 Sep 2022 20:36:35 +0200 Subject: [PATCH] fix: move React `flushSync` to microtask (#3188) To avoid seeing the `Warning: flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.` error, we need to move the `flushSync()` code that avoids automatic batching to a microtask to not fire a lifecycle event `setState()` during rendering. Fixes warning introduced in #2985 --- packages/react/src/ReactRenderer.tsx | 42 +++++++++++++++------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/packages/react/src/ReactRenderer.tsx b/packages/react/src/ReactRenderer.tsx index f38ceb554ba..6a497efc867 100644 --- a/packages/react/src/ReactRenderer.tsx +++ b/packages/react/src/ReactRenderer.tsx @@ -78,15 +78,17 @@ export class ReactRenderer { this.reactElement = - flushSync(() => { - if (this.editor?.contentComponent) { - this.editor.contentComponent.setState({ - renderers: this.editor.contentComponent.state.renderers.set( - this.id, - this, - ), - }) - } + queueMicrotask(() => { + flushSync(() => { + if (this.editor?.contentComponent) { + this.editor.contentComponent.setState({ + renderers: this.editor.contentComponent.state.renderers.set( + this.id, + this, + ), + }) + } + }) }) } @@ -100,16 +102,18 @@ export class ReactRenderer { } destroy(): void { - flushSync(() => { - if (this.editor?.contentComponent) { - const { renderers } = this.editor.contentComponent.state - - renderers.delete(this.id) - - this.editor.contentComponent.setState({ - renderers, - }) - } + queueMicrotask(() => { + flushSync(() => { + if (this.editor?.contentComponent) { + const { renderers } = this.editor.contentComponent.state + + renderers.delete(this.id) + + this.editor.contentComponent.setState({ + renderers, + }) + } + }) }) } }