From 47f5169ba2e1350049d2da1f24b63f94303cf7c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Po=C5=9Bpiech?= Date: Sat, 20 Apr 2024 21:30:34 +0200 Subject: [PATCH] fixed working with react 18 strict mode --- packages/uniforms/src/BaseForm.tsx | 45 ++++++++++++++++-------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/packages/uniforms/src/BaseForm.tsx b/packages/uniforms/src/BaseForm.tsx index 79df4f87b..90347ebc0 100644 --- a/packages/uniforms/src/BaseForm.tsx +++ b/packages/uniforms/src/BaseForm.tsx @@ -94,14 +94,6 @@ export class BaseForm< if (this.delayId) { clearTimeout(this.delayId); } - - // There are at least 4 places where we'd need to check, whether or not we - // actually perform `setState` after the component gets unmounted. Instead, - // we override it to hide the React warning. Also because React no longer - // will raise it in the newer versions. - // https://github.com/facebook/react/pull/22114 - // https://github.com/vazco/uniforms/issues/1152 - this.setState = () => {}; } delayId?: ReturnType | undefined; @@ -235,12 +227,14 @@ export class BaseForm< this.delayId = setTimeout(() => { // ...and wait for all scheduled `setState`s to commit. This is required // for AutoForm to validate correct model, waiting in `onChange`. - this.setState( - () => null, - () => { - this.onSubmit(); - }, - ); + if (this.mounted) { + this.setState( + () => null, + () => { + this.onSubmit(); + }, + ); + } }, this.props.autosaveDelay); } } @@ -256,10 +250,12 @@ export class BaseForm< } onReset() { - // @ts-expect-error - // It's bound in constructor. - // eslint-disable-next-line @typescript-eslint/unbound-method - this.setState(this.__reset); + if (this.mounted) { + // @ts-expect-error + // It's bound in constructor. + // eslint-disable-next-line @typescript-eslint/unbound-method + this.setState(this.__reset); + } } onSubmit(event?: SyntheticEvent) { @@ -268,16 +264,23 @@ export class BaseForm< event.stopPropagation(); } - this.setState(state => (state.submitted ? null : { submitted: true })); + if (this.mounted) { + this.setState(state => (state.submitted ? null : { submitted: true })); + } const result = this.props.onSubmit(this.getModel('submit')); if (!(result instanceof Promise)) { return Promise.resolve(); } - this.setState({ submitting: true }); + if (this.mounted) { + this.setState({ submitting: true }); + } + return result.finally(() => { - this.setState({ submitting: false }); + if (this.mounted) { + this.setState({ submitting: false }); + } }); }