You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提交表单后重置Formik表单仍显示必填错误,如何清除?

Fix: Formik Shows Required Error After Resetting Form

Let's break down why your current approach isn't working and fix the issue step by step.

The Root Problem

When you call helpers.resetForm(), Formik resets the form values to your initialValues, but it may also re-run validation against your Yup schema (since you've defined one). Since your locationName field is required, the empty value after reset triggers the error again. Your setErrors({}) call gets overwritten by this post-reset validation, which is why it doesn't work.

Solution 1: Reset with Explicit State Clearing

Modify your handleSubmitForm to wait for the GraphQL mutation to complete, then reset the form while explicitly clearing touched and errors state, and disabling post-reset validation:

const handleSubmitForm = async (
  values: FormValues,
  helpers: FormikHelpers<FormValues>,
) => {
  try {
    // Wait for the mutation to finish before resetting
    await editLocationName({
      variables: {
        favouritePlaceId: route.params.id,
        input: {customisedName: values.locationName}
      },
    });

    // Reset form and clear all validation state
    helpers.resetForm({
      touched: {},
      errors: {},
      isValidating: false, // Prevent automatic validation after reset
    });
  } catch (error) {
    // Handle mutation failures (e.g., show an error toast)
    console.error("Failed to update location name:", error);
  }
};

Solution 2: Show Errors Only When Fields Are Touched

Even if validation runs after reset, you can prevent the error from displaying by tying it to the touched state. This aligns with your requirement to only show errors when the user submits without input (since submitting marks fields as touched).

Update your Formik render logic to check both touched and errors:

<Formik
  initialValues={initialValues}
  onSubmit={handleSubmitForm}
  validationSchema={validationSchema}
>
  {({ handleChange, handleBlur, handleSubmit, values, touched, errors }) => (
    <View style={styles.searchFieldContainer}>
      <View style={styles.form}>
        <FieldInput
          handleChange={handleChange}
          handleBlur={handleBlur}
          value={values.locationName}
          fieldType="locationName"
          placeholderText="Neuer Name"
        />
        {/* Only show error if the field was touched AND has an error */}
        {touched.locationName && errors.locationName && (
          <ErrorText errorMessage={errors.locationName} />
        )}
      </View>
      <View style={styles.buttonContainer}>
        <ActionButton buttonText="Save" onPress={handleSubmit} />
      </View>
    </View>
  )}
</Formik>

Why Your Original setErrors({}) Didn't Work

resetForm() triggers a re-validation cycle when a validationSchema is present. Your setErrors({}) runs before this cycle completes, so the new validation errors immediately overwrite your empty errors object. By including errors: {} directly in the resetForm parameters, you ensure the state stays clear after reset.

内容的提问来源于stack exchange,提问作者user13101751

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:47:29