简体   繁体   中英

How to use async onFinish method with Ant Design Form

When I set an async function on onFinish param, VSCode says the warning message below

(JSX attribute) onFinish?: ((values: Store) => void) | undefined
Type '(values: NannyProfileUpdateType) => Promise<void>' is not assignable to type '(values: Store) => void'.
  Types of parameters 'values' and 'values' are incompatible.
    Type 'Store' is missing the following properties from type 'NannyProfileUpdateType': firstName, lastName, email, doesStartASA, and 32 more.ts(2322)
Form.d.ts(15, 5): The expected type comes from property 'onFinish' which is declared here on type 'IntrinsicAttributes & FormProps & RefAttributes<FormInstance>'

How can I implement an async function?

My code is like this.

const onFinish = async (values) => {
  setIsSubmitting(true);
  const response = await Api.get(worker.id as number);
  setWorker(response.worker);
  openSnackbar();
  setIsSubmitting(false);
};


return (
  <Form
    layout="vertical"
    hideRequiredMark
    onFinish={onFinish}
    initialValues={worker}
  >
    <Row gutter={16}>
      <Col span={12}>
      ・
      ・
      ・
);

onFinish requires a function callback instead of Promise.

You can use the arrow function. But don't forget to use Promise actions in it if you need it.

<Form
    layout="vertical"
    hideRequiredMark
    onFinish={(values) => onFinish(values)}
    initialValues={worker}
  >

Since you don't have any Promise logic in your onFinish function it doesn't make sense to use async/await in it.

So you could use.then functionality without async/await.

const onFinish = (values) => {
  setIsSubmitting(true);
  Api.get(worker.id as number)
     .then(response => {
       setWorker(response.worker);
       openSnackbar();
     })
     .catch((error) => setError(error))
     .finally(() => {
       setIsSubmitting(false);
     });
};


return (
  <Form
    layout="vertical"
    hideRequiredMark
    onFinish={onFinish}
    initialValues={worker}
  >
    <Row gutter={16}>
      <Col span={12}>
      ・
      ・
      ・
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM