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
This commit is contained in:
Daniel Spitzer
2022-09-13 20:36:35 +02:00
committed by GitHub
parent 1cc75c058c
commit 9093cdfcf5

View File

@@ -78,15 +78,17 @@ export class ReactRenderer<R = unknown, P = unknown> {
this.reactElement = <Component {...props } />
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<R = unknown, P = unknown> {
}
destroy(): void {
flushSync(() => {
if (this.editor?.contentComponent) {
const { renderers } = this.editor.contentComponent.state
queueMicrotask(() => {
flushSync(() => {
if (this.editor?.contentComponent) {
const { renderers } = this.editor.contentComponent.state
renderers.delete(this.id)
renderers.delete(this.id)
this.editor.contentComponent.setState({
renderers,
})
}
this.editor.contentComponent.setState({
renderers,
})
}
})
})
}
}