【问题标题】:Reset formik form using mutations react query使用突变反应查询重置formik表单
【发布时间】:2021-08-15 20:41:48
【问题描述】:

我有一个使用 formik 和 react 查询的表单。我想在成功时重置表单。

有没有办法将 resetForm 函数作为参数传递给 onSuccess ?

const mutation = useMutation(
  (newUser) =>
    axios.post(`/api/accounts`, newUser),
  {
    onSuccess: (data) => {
      alert(JSON.stringify(data));
      router.push(`/confirm-email?email=${data.email}`);
    },
    onError: (error) => {
      if (error.response && error.response.data.message) {
        openSnackbar(error.response.data.message);
      } else {
        openSnackbar('Something went wrong, please retry later');
      }
    },
  }
);

表格

<Formik
  onSubmit={(values, { setSubmitting, resetForm }) => {
    mutation.mutate(values);
    setSubmitting(false);
  }}
>
  ...
</Formik>

【问题讨论】:

    标签: reactjs formik react-query


    【解决方案1】:

    您可以在 useMutation 和 onMutate 中设置 onSuccess:

    <Formik
      onSubmit={(values, { setSubmitting, resetForm }) => {
        mutation.mutate(values, { onSuccess: ()=> resetForm() });
        setSubmitting(false);
      }}
    >
      ...
    </Formik>
    

    【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2019-08-03
    • 1970-01-01
    • 2023-01-20
    • 2022-08-18
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多