Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setFieldValue onSubmit in Formik

I'm using formik with @jbuschke/formik-antd and react-input-mask. I have a mask +7 (___) ___-__-__ applied to one of the inputs and I need to parse it onSubmit to remove unnecessary symbols.

I've defined a const changedValue, which is then used in setFieldValue, but I get the following error:

Invariant Violation
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Here is my code and the demo:

const CloseForm = () => (
  <Formik
    initialValues={{ phone: "", email: "" }}
    onSubmit={(values, { setSubmitting, setFieldValue }) => {
      const changedValue = values.phone.replace(/\(|\)|\s|-/g, "");
      setTimeout(() => {
        setFieldValue("phone", changedValue);
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 400);
    }}
    validate={validatePhone}
  >
    {({ isSubmitting, values, handleChange }) => {
      return (
        <Form>
          <FormItem name="phone" label="Phone" required="true">
            <CustomInput
              mask="+7 (999) 999-99-99"
              name="phone"
              onChange={handleChange}
            />
          </FormItem>
          <FormItem name="email" label="Email">
            <Input name="email" />
          </FormItem>
          <SubmitButton type="primary" disabled={isSubmitting}>
            Submit
          </SubmitButton>
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      );
    }}
  </Formik>
);

How can I fix this problem? Or may be there is a better way to use setFieldValue to parse the value?

like image 503
jupiteror Avatar asked Jul 25 '19 18:07

jupiteror


1 Answers

You can modify the value you are going to submit without changing the field, for example:

onSubmit={values => {
  const phone = values.phone.replace(/\(|\)|\s|-/g, "")
  const valuesToSend = { ...values, phone }

  alert(JSON.stringify(valuesToSend, null, 2))
}}
like image 99
CD.. Avatar answered Oct 10 '22 06:10

CD..