Formik How to Access Initial Values

Aug 9, 2024

Formik How to Access Initial Values

Formik is a powerful library for managing forms in React applications. It simplifies form handling, validation, and submission, allowing developers to focus on building user interfaces. In this blog post, we will explore how to access initial values in Formik, specifically addressing the keywords "formik how to load initial value without commit," "formik field," and "handleBlur not trigger validation second true."

Understanding Initial Values in Formik

Initial values in Formik are the default values that your form fields will hold when the form is first rendered. These values are crucial for setting up the form correctly, especially when dealing with editing existing data.

Setting Up Initial Values

To set initial values in Formik, you can use the initialValues prop. Here’s a basic example:

import React from 'react';
import { Formik, Form, Field } from 'formik';

const MyForm = () => (
  <Formik
    initialValues={{
      firstName: '',
      lastName: '',
      email: '',
    }}
    onSubmit={(values) => {
      // Handle form submission
      console.log(values);
    }}
  >
    <Form>
      <Field name="firstName" placeholder="First Name" />
      <Field name="lastName" placeholder="Last Name" />
      <Field name="email" placeholder="Email" type="email" />
      <button type="submit">Submit</button>
    </Form>
  </Formik>
);

In this example, the form initializes with empty fields for firstName, lastName, and email.

Accessing Initial Values Without Committing

Sometimes, you may want to access the initial values without committing the form. This can be particularly useful when you need to compare the current values with the initial values before submission. To achieve this, you can use the useFormikContext hook, which gives you access to the Formik context, including the initial values. Here’s how you can do it:

import React from 'react';
import { Formik, Form, Field, useFormikContext } from 'formik';

const MyForm = () => {
  const { initialValues } = useFormikContext();

  const handleSubmit = (values) => {
    // Compare values with initialValues
    if (JSON.stringify(values) !== JSON.stringify(initialValues)) {
      console.log('Values have changed:', values);
    } else {
      console.log('No changes detected');
    }
  };

  return (
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
      }}
      onSubmit={handleSubmit}
    >
      <Form>
        <Field name="firstName" placeholder="First Name" />
        <Field name="lastName" placeholder="Last Name" />
        <Field name="email" placeholder="Email" type="email" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};

Handling Field Validation with handleBlur

Formik'shandleBlurfunction is designed to trigger validation when a field loses focus. However, there are scenarios where you might want to prevent validation from triggering under certain conditions. For instance, if you want to avoid validation when clicking outside the form, you can manage this behavior by controlling thevalidateOnBlurprop.

Here’s an example of how to prevent validation on blur:

<Formik
  initialValues={{
    firstName: '',
    lastName: '',
    email: '',
  }}
  validateOnBlur={false} // Disable validation on blur
  onSubmit={(values) => {
    console.log(values);
  }}
>
  {({ handleBlur }) => (
    <Form>
      <Field name="firstName" onBlur={handleBlur} placeholder="First Name" />
      <Field name="lastName" onBlur={handleBlur} placeholder="Last Name" />
      <Field name="email" onBlur={handleBlur} placeholder="Email" type="email" />
      <button type="submit">Submit</button>
    </Form>
  )}
</Formik>

Loading Initial Values from an API

In real-world applications, you often need to load initial values from an API. Formik provides a way to handle this through theenableReinitializeprop. When set totrue, Formik will reset the form whenever theinitialValuesprop changes.Here’s how you can load initial values asynchronously:

import React, { useEffect, useState } from 'react';
import { Formik, Form, Field } from 'formik';

const MyForm = () => {
  const [initialValues, setInitialValues] = useState({
    firstName: '',
    lastName: '',
    email: '',
  });

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('/api/user');
      const data = await response.json();
      setInitialValues(data);
    };

    fetchData();
  }, []);

  return (
    <Formik
      initialValues={initialValues}
      enableReinitialize // Reinitialize form when initialValues change
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      <Form>
        <Field name="firstName" placeholder="First Name" />
        <Field name="lastName" placeholder="Last Name" />
        <Field name="email" placeholder="Email" type="email" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};

Conclusion

In this blog post, we explored how to access initial values in Formik, load them without committing changes, and manage field validation behavior. By understanding these concepts, you can create more dynamic and user-friendly forms in your React applications.

Utilizing Formik effectively can significantly enhance your form handling capabilities, making it easier to manage complex forms with minimal boilerplate code. Whether you're loading initial values from an API or managing validation behavior, Formik provides the tools you need to create robust forms.