0
votes

I'm new to Formik and not sure how to access the initialValues in my submit handler in order to compare it with values before submitting.

If someone could show how this is done in the basic Formik example below I'd be happy.

const Basic = () => (
  <div>
    <h1>Sign Up</h1>
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
      }}
      onSubmit={async (values) => {
        await new Promise((r) => setTimeout(r, 500));
        // GET initialValues HERE... 
        alert(JSON.stringify(values, null, 2));
      }}
    >
      <Form>
        <label htmlFor="firstName">First Name</label>
        <Field id="firstName" name="firstName" placeholder="Jane" />

        <label htmlFor="lastName">Last Name</label>
        <Field id="lastName" name="lastName" placeholder="Doe" />

        <label htmlFor="email">Email</label>
        <Field
          id="email"
          name="email"
          placeholder="[email protected]"
          type="email"
        />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </div>
);

ReactDOM.render(<Basic />, document.getElementById('root'));

I know there are a few threads out there explaining how to do it with HOCs etc. , like https://medium.com/@MelkorNemesis/how-to-check-if-formik-values-have-changed-on-submit-2c6ee89992ec but my React knowledge is to low to translate this into the basic function above. FWIW I also think it would be beneficial to have this as an example in the Formik docs, seems like a pretty common use case.

1
I found this answer is pretty close to what you are looking for: stackoverflow.com/a/59619976/5972355Tung Pham

1 Answers

1
votes

You can declare an object inside your component and pass it to Formik initialValues prop.

const Basic = () => {
  const initialValues = {
    firstName: '',
    lastName: '',
    email: '',
  };
  return (
    <div>
      <h1>Sign Up</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={async (values) => {
          // compare initialValues and values here
        }}
      >
        <Form>
          <label htmlFor="firstName">First Name</label>
          <Field id="firstName" name="firstName" placeholder="Jane" />

          <label htmlFor="lastName">Last Name</label>
          <Field id="lastName" name="lastName" placeholder="Doe" />

          <label htmlFor="email">Email</label>
          <Field
            id="email"
            name="email"
            placeholder="[email protected]"
            type="email"
          />
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};

ReactDOM.render(<Basic />, document.getElementById('root'));