简体   繁体   中英

Reset Form After Submitting

I have a react form that calls a graphql mutation when the button is clicked. After the button is clicked and the mutation is completed, the text in the form is still there. So in order to run a new mutation, the user will have to manually remove the text written in the text fields.

Is there any way to automatically reset the text fields once the form is submitted?

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation<DeleteUserReponse>(REMOVE_USER);

  let submitForm = (email: string) => {
    setIsSubmitted(true);
    removeUser({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<DeleteUserReponse>) => {
        if (data !== null && data !== undefined){
        setIsRemoved(true);
      }})
      .catch((error: { message: string }) => {
        setIsRemoved(false);
        setErrorMessage(error.message);
      });
  };

  const initialValues={ email: '' }
  return (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        //initialValues={{ email: '' }}
        initialValues={initialValues}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
          initialValues={initialValues}
        }}
        validationSchema={schema}>
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched,
          } = props;
          const change = (name: string, e: FormEvent) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <div>
              <form
                style={{ width: '100%' }}
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </form>
              {isSubmitted && StatusMessage(isRemoved, errorMessage)}
            </div>
          );
        }}
      </Formik>
    </div>
  );
}

Try reusing your initial state, something like this:

const INITIAL_STATE = { email: '' };

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation<DeleteUserReponse>(REMOVE_USER);

  let submitForm = (email: string) => {
    setIsSubmitted(true);
    removeUser({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<DeleteUserReponse>) => {
        if (data !== null && data !== undefined){
        setIsRemoved(true);
      }})
      .catch((error: { message: string }) => {
        setIsRemoved(false);
        setErrorMessage(error.message);
      });
  };

  return (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ ...INITIAL_STATE }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
          actions.setValues({ ...INITIAL_STATE });
        }}
        validationSchema={schema}>
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched,
          } = props;
          const change = (name: string, e: FormEvent) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <div>
              <form
                style={{ width: '100%' }}
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </form>
              {isSubmitted && StatusMessage(isRemoved, errorMessage)}
            </div>
          );
        }}
      </Formik>
    </div>
  );
}

Although I've also seen resetForm method on second parameter of onSubmit , but haven't tested it how it works, so you can try that also.

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