This is a glossary of all the common issues in JaredPalmer Formik
  • 28-Dec-2022
Lightrun Team
Author Lightrun Team
Share
This is a glossary of all the common issues in JaredPalmer Formik

Troubleshooting Common Issues in JaredPalmer Formik

Lightrun Team
Lightrun Team
28-Dec-2022

Project Description

 

Formik is a popular open-source library for building forms in React. It was developed by Jared Palmer, a software engineer and open source developer. Formik aims to make it easier to build and manage forms in React by providing a simple and intuitive API. It includes a number of features that make it easier to work with forms, such as:

  • Support for handling form state and validation
  • Tools for managing form submissions and errors
  • A declarative API that makes it easy to define and customize forms

Formik is widely used in the React community and is considered a standard tool for building forms in React. It is easy to use and can save developers time and effort when building forms in their React projects.

Troubleshooting JaredPalmer Formik with the Lightrun Developer Observability Platform

 

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.
  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

The following issues are the most popular issues regarding this project:

Yup schema.validate() options, show every error of a field at the same time

 

In Formik, you can use the validate prop to specify a function that will be used to validate the form. This function can be used to perform any necessary validation, including using a Yup schema to validate the form data.

If you want to show every error of a field at the same time when using a Yup schema with the validate prop, you can pass the abortEarly: false option to the validate method. This will cause the validate method to return all of the validation errors for a field, rather than just the first one.

Here is an example of how you might use this option:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  username: Yup.string().required('Username is required'),
  password: Yup.string().required('Password is required')
});

const validate = values => {
  try {
    schema.validate(values, { abortEarly: false });
  } catch (error) {
    return error.inner.reduce((errors, err) => {
      errors[err.path] = err.message;
      return errors;
    }, {});
  }
  return {};
};

<Formik
  initialValues={{ username: '', password: '' }}
  onSubmit={(values, actions) => {
    console.log(values);
    actions.setSubmitting(false);
  }}
  validate={validate}
  render={props => (
    <form onSubmit={props.handleSubmit}>
      <Field name="username" type="text" />
      <ErrorMessage name="username" />
      <Field name="password" type="password" />
      <ErrorMessage name="password" />
      <button type="submit">Submit</button>
    </form>
  )}
/>

This will cause the validate function to return an object containing all of the validation errors for each field, which will be displayed to the user.

Set default Yup validation context to form values

 

If you want to set the default Yup validation context to the form values, you can use the setContext method to set the context of the Yup schema. The context will be passed to the validate method as an argument, and you can use it to set the default values for the schema.

Here is an example of how you might use this feature:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  username: Yup.string().required('Username is required'),
  password: Yup.string().required('Password is required')
});

const validate = (values, context) => {
  schema.setContext(context);
  try {
    schema.validateSync(values, { strict: true });
  } catch (error) {
    return error.inner.reduce((errors, err) => {
      errors[err.path] = err.message;
      return errors;
    }, {});
  }
  return {};
};

<Formik
  initialValues={{ username: '', password: '' }}
  onSubmit={(values, actions) => {
    console.log(values);
    actions.setSubmitting(false);
  }}
  validate={validate}
  render={props => (
    <form onSubmit={props.handleSubmit}>
      <Field name="username" type="text" />
      <ErrorMessage name="username" />
      <Field name="password" type="password" />
      <ErrorMessage name="password" />
      <button type="submit">Submit</button>
    </form>
  )}
/>

This will cause the validate function to use the default values specified in the context when validating the form data with the Yup schema.

How do I update initialValues with values from props/api request

 

In Formik, you can use the initialValues prop to specify the initial values for the form fields. These values can be static, or you can use them to store dynamic data, such as data retrieved from an API request.

To update the initialValues with values from props or an API request, you can use the useEffect hook to perform the update when the component mounts or when the props or API response change.

Here is an example of how you might do this:

import { useEffect } from 'react';

function MyForm(props) {
  const [initialValues, setInitialValues] = useState({});

  useEffect(() => {
    // Update initialValues with values from props
    setInitialValues({
      field1: props.value1,
      field2: props.value2
    });
  }, [props]);

  useEffect(() => {
    // Perform API request and update initialValues with response data
    async function fetchData() {
      const response = await fetch('/api/data');
      const data = await response.json();
      setInitialValues({
        field1: data.value1,
        field2: data.value2
      });
    }
    fetchData();
  }, []);

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={(values, actions) => {
        console.log(values);
        actions.setSubmitting(false);
      }}
      render={props => (
        <form onSubmit={props.handleSubmit}>
          <Field name="field1" type="text" />
          <Field name="field2" type="text" />
          <button type="submit">Submit</button>
        </form>
      )}
    />
  );
}

In this example, the initialValues are updated with values from the component’s props when the props change, and they are also updated with data from an API request when the component mounts. This allows you to keep the form fields up to date with the latest data.

React Formik updating one field based on another

 

In Formik, you can use the setFieldValue function to update the value of a form field based on the value of another field.

To do this, you can use the useField hook to access the value of the field that you want to update, and then use the setFieldValue function to set the value of the other field.

Here is an example of how you might do this:

import { useField } from 'formik';

function MyForm() {
  const [field1, , { setFieldValue }] = useField('field1');
  const [field2, , { setFieldValue: setFieldValue2 }] = useField('field2');

  useEffect(() => {
    // Update field2 based on field1
    setFieldValue2(field1.value);
  }, [field1.value]);

  return (
    <Formik
      onSubmit={(values, actions) => {
        console.log(values);
        actions.setSubmitting(false);
      }}
      render={props => (
        <form onSubmit={props.handleSubmit}>
          <Field name="field1" type="text" />
          <Field name="field2" type="text" />
          <button type="submit">Submit</button>
        </form>
      )}
    />
  );
}

In this example, the value of field2 is updated to the value of field1 whenever the value of field1 changes. This allows you to keep the fields in sync and ensure that they have the correct values.

input type=’number’ actually returns empty string for empty input

 

Yes, that is correct. If you are using a <input type="number"> element with the Formik form library, the value of the input field will be an empty string when the user has not entered any input.

This is because the value of the <input> element is always a string, and if the user has not entered any input, the value will be an empty string. Formik will treat an empty string as an uninitialized value and will not include it in the form’s values object unless you have specified a default value for the input field.

You can handle this case by using Formik’s validate prop to add validation logic that checks for an empty string and sets an error message if the user has not entered any input. You can also use the validateOnBlur prop to trigger validation only when the user leaves the input field, rather than on every change.

Here is an example of how you could use the validate prop to require that the user enters a value for the <input type="number"> field:

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

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      validate={values => {
        const errors = {};
        if (values.number === '') {
          errors.number = 'Required';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the validate function is called whenever the form values change, and it checks for an empty string in the number field. If the number field is an empty string, the validate function sets an error message for the field. The error message will be displayed to the user if you are using Formik’s ErrorMessage component to display validation errors.

Fields are not set as touched before Submit except for when none are “manually” touched

 

Yes, that is correct. In Formik, the touched object tracks which form fields have been “touched” by the user, meaning that the user has focused and then blurred the field. By default, Formik does not consider a field to be touched until the user manually interacts with it.

This means that if you submit a Formik form without the user interacting with any of the fields, the touched object will be an empty object, and none of the fields will be marked as touched. This can be an issue if you want to display validation errors for all fields when the form is submitted, regardless of whether the user has interacted with them.

To display validation errors for all fields on submit, you can set the validateOnBlur prop to false and the validateOnChange prop to true. This will cause Formik to validate the form on every change and submit, rather than only when the user leaves a field.

You can also use the setTouched function to manually set the touched object to include all fields. This can be useful if you want to mark all fields as touched and display validation errors when the form is submitted.

Here is an example of how you could use the setTouched function to mark all fields as touched when the form is submitted:

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

function MyForm() {
  const [touchedAllFields, setTouchedAllFields] = useState(false);

  return (
    <Formik
      initialValues={{ number: '' }}
      validate={values => {
        const errors = {};
        if (values.number === '') {
          errors.number = 'Required';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting, setTouched }) => {
        setTimeout(() => {
          if (!touchedAllFields) {
            setTouched(Object.keys(values).reduce((acc, key) => ({ ...acc, [key]: true }), {}));
            setTouchedAllFields(true);
          }
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the onSubmit function uses the setTouched function to mark all fields as touched before submitting the form. The form is only submitted once, even if the user does not interact with any of the fields, because the touchedAllFields state variable is used to track whether the form has already been submitted. This will cause Formik to display validation errors for all fields on submit.

No onChange prop for <Formik/>?

 

The <Formik> component does not have an onChange prop, but it does have an onChange event handler that you can use to perform an action when the form values change. The onChange event handler is called whenever the form values change, whether by user input or programmatically.

Here is an example of how you can use the onChange event handler to log the form values to the console whenever they change:

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

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      onChange={(values, setValues) => {
        console.log(values);
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the onChange event handler is called whenever the form values change, and it logs the values to the console. You can use the onChange event handler to perform any action you like whenever the form values change.

Keep in mind that the onChange event handler will be called for every change to the form values, not just when the user interacts with a form field. If you only want to perform an action when the user interacts with a specific field, you can use the onChange prop of the <Field> component to specify a change handler for that field.

How disable the auto reset form on submit in formik?

 

By default, Formik will reset the form to its initial values after a successful submission. If you want to prevent the form from resetting after submission, you can use the resetForm function from the formik object and pass it false as an argument.

Here is an example of how you can disable the form reset after submission:

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

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      onSubmit={(values, { setSubmitting, resetForm }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          resetForm(false);  // disable form reset
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the resetForm function is called with false as an argument in the onSubmit handler, which disables the form reset after submission. The form will retain its current values after submission, rather than being reset to the initial values.

Keep in mind that disabling the form reset may not always be the desired behavior, as it can lead to confusion for the user if the form does not reset after submission. Consider carefully whether it is appropriate to disable the form reset in your use case.

Handle multiple errors returned by Yup

 

Yup is a JavaScript library for object schema validation, which can be used with Formik to validate form values. If you are using Yup with Formik, you can use the validate prop to specify a Yup schema that defines the validation rules for your form.

If your Yup schema defines multiple validation rules and one or more of them fail, Yup will return an object that contains all of the validation errors. Formik will automatically display these errors to the user if you are using the ErrorMessage component to display validation errors.

Here is an example of how you can use Yup with Formik to handle multiple validation errors:

import * as Yup from 'yup';
import { Formik, Form, Field, ErrorMessage } from 'formik';

const validationSchema = Yup.object().shape({
  number: Yup.number()
    .required('Number is required')
    .min(10, 'Number must be at least 10')
    .max(100, 'Number must be at most 100'),
});

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      validationSchema={validationSchema}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <ErrorMessage name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the Yup schema defines three validation rules for the number field: it must be a required field, it must be a number, and it must be between 10 and 100. If any of these validation rules fail, Yup will return an object that contains all of the validation errors. The ErrorMessage component will automatically display the appropriate error message to the user based on the validation errors returned by Yup.

You can also use the validate prop to specify a custom validation function that handles multiple validation errors. The validate function will receive the form values as an argument, and it should return an object that contains any validation errors. Formik will automatically display these errors to the user if you are using the ErrorMessage component.

How to show an additional error message when validation fails on submit

 

If you want to display an additional error message when validation fails on submit in a Formik form, you can use the submitCount property of the formik object to check whether the form has been submitted, and then use the setFieldError function to set an error message for a specific field.

Here is an example of how you can show an additional error message when validation fails on submit:

import { Formik, Form, Field, ErrorMessage } from 'formik';

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      validate={values => {
        const errors = {};
        if (values.number === '') {
          errors.number = 'Number is required';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting, setFieldError, submitCount }) => {
        setTimeout(() => {
          if (submitCount > 0 && values.number === '') {
            setFieldError('number', 'Please enter a valid number');
          } else {
            alert(JSON.stringify(values, null, 2));
          }
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <ErrorMessage name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the onSubmit handler checks the submitCount property to see if the form has been submitted, and it checks the value of the number field to see if it is an empty string. If the form has been submitted and the number field is an empty string, the setFieldError function is used to set an additional error message for the number field. The ErrorMessage component will automatically display this error message to the user.

Keep in mind that this additional error message will only be displayed if the form has been submitted and the number field is an empty string. You can customize this behavior as needed to fit your use case.

Formik automatically converts input type number value to float

 

Yes, that is correct. Formik will automatically convert the value of an <input type="number"> field to a JavaScript Number type, which includes both integers and floating point numbers.

If the user enters a valid number into the <input type="number"> field, Formik will automatically convert the value to a JavaScript Number type and include it in the form’s values object. If the user enters an invalid number or an empty string, Formik will set the value to NaN (Not a Number) and include it in the form’s values object.

You can use the parseInt or parseFloat functions to explicitly convert the value to an integer or a floating point number, respectively. Here is an example of how you can use parseFloat to convert the value of an <input type="number"> field to a floating point number:

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

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      onSubmit={(values, { setSubmitting }) => {
        const number = parseFloat(values.number);
        setTimeout(() => {
          alert(`Number: ${number}`);
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the onSubmit handler uses the parseFloat function to convert the number field value to a floating point number, and then displays the number in an alert. You can use similar logic to convert the value to an integer using the parseInt function.

Keep in mind that the parseInt and parseFloat functions will return NaN if the input string is not a valid number. You may want to add additional validation logic to handle this case.

Field level validation dependent on other fields

 

In Formik, you can use the validate prop to specify a custom validation function that can perform field level validation based on the values of other fields. The validate function will receive the form values as an argument, and it should return an object that contains any validation errors.

Here is an example of how you can use the validate prop to perform field level validation based on the values of other fields:

import { Formik, Form, Field, ErrorMessage } from 'formik';

function MyForm() {
  return (
    <Formik
      initialValues={{ password: '', confirmPassword: '' }}
      validate={values => {
        const errors = {};
        if (values.password !== values.confirmPassword) {
          errors.confirmPassword = 'Passwords do not match';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="password" name="password" />
          <Field type="password" name="confirmPassword" />
          <ErrorMessage name="confirmPassword" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the validate function checks the values of the password and confirmPassword fields, and it sets an error for the confirmPassword field if the two values do not match. The ErrorMessage component will automatically display the error message to the user if the validation fails.

You can use similar logic to perform field level validation based on the values of other fields in your form. The validate function has access to all of the form values, so you can use the values of any fields in your validation logic.

yup validation schema

 

Yup is a JavaScript library for object schema validation that can be used with Formik to validate form values. If you are using Yup with Formik, you can use the validationSchema prop to specify a Yup schema that defines the validation rules for your form.

Here is an example of how you can use a Yup schema with Formik:

import * as Yup from 'yup';
import { Formik, Form, Field, ErrorMessage } from 'formik';

const validationSchema = Yup.object().shape({
  number: Yup.number().required('Number is required'),
});

function MyForm() {
  return (
    <Formik
      initialValues={{ number: '' }}
      validationSchema={validationSchema}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="number" name="number" />
          <ErrorMessage name="number" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the Yup schema defines a validation rule for the number field, requiring it to be a number. If the user enters an invalid number or an empty string, Yup will return an error indicating that the field is required. The ErrorMessage component will automatically display this error message to the user.

You can use the full range of validation functions and options provided by Yup in your schema to define complex validation rules for your form. For more information on using Yup with Formik, you can refer to the Formik documentation and the Yup documentation.

TypeError: Cannot read property ‘validate’ of undefined

 

The TypeError: Cannot read property 'validate' of undefined error in Formik can occur if you are trying to use the validate prop, but Formik has not been properly initialized.

There are a few common causes for this error:

  1. You are using the validate prop, but you have not imported the Formik component. Make sure you have imported Formik at the top of your file:
import { Formik } from 'formik';
  1. You are not wrapping your form fields with the <Formik> component. Make sure you are using the <Formik> component to wrap your form fields:
<Formik>
  <Form>
    <Field />
  </Form>
</Formik>
  1. You are using the validate prop, but you have not specified a validation function. Make sure you are passing a validation function to the validate prop:
<Formik validate={values => { /* validation logic */ }}>
  <Form>
    <Field />
  </Form>
</Formik>

If you are still experiencing this error after checking these items, there may be another issue causing the problem. Make sure you have followed the Formik documentation and examples carefully, and double-check your code for any typos or mistakes.

setFieldValue to undefined deletes the value from values and prevents errors from showing / touched being updated on submit

 

In Formik, the setFieldValue function can be used to set the value of a specific field in the form. If you pass undefined as the value to setFieldValue, it will delete the field from the form’s values object and reset the field to its initial value.

Here is an example of how you can use setFieldValue to delete a field from the form’s values object:

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

function MyForm() {
  const [showField, setShowField] = useState(true);

  return (
    <Formik
      initialValues={{ number: '' }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting, setFieldValue }) => (
        <Form>
          {showField && (
            <Field type="number" name="number" />
          )}
          <button
            type="button"
            onClick={() => {
              setShowField(!showField);
              setFieldValue('number', undefined);
            }}
          >
            Toggle Field
          </button>
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the setFieldValue function is used to delete the number field from the form’s values object when the user clicks the “Toggle Field” button. The field

Formik doesn’t update isValidating onBlur and onChange, only onSubmit

 

In Formik, the isValidating property is a boolean that indicates whether the form is currently being validated. By default, Formik updates the isValidating property only when the form is submitted.

However, you can use the validateOnBlur and validateOnChange props to specify that Formik should validate the form’s values when the user blurs a field or changes a field, respectively. If either of these props is set to true, Formik will update the isValidating property when the corresponding event occurs.

onChange and onBlur causes component to re-render

 

In Formik, the onChange and onBlur props can be used to specify callback functions that will be called when the value of a form field changes or when the field loses focus, respectively. These props can be useful for performing additional actions or validation when the form field value changes.

However, it is important to keep in mind that using the onChange and onBlur props can cause the component to re-render, which can have performance implications if the component is being re-rendered unnecessarily.

One way to minimize the impact of re-renders is to use the useCallback hook to create a memoized version of the callback function. This will ensure that the callback function is only recreated if one of its dependencies changes.

Here is an example of how you can use the useCallback hook to minimize re-renders when using the onChange and onBlur props:

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

function MyForm() {
  const handleChange = useCallback(
    (event, formik) => {
      formik.setFieldValue(event.target.name, event.target.value);
      // Perform additional actions on change
    },
    []
  );

  const handleBlur = useCallback(
    (event, formik) => {
      formik.setFieldTouched(event.target.name, true);
      // Perform additional actions on blur
    },
    []
  );

  return (
    <Formik
      initialValues={{ number: '' }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting, setFieldValue, setFieldTouched }) => (
        <Form>
          <Field
            type="number"
            name="number"
            onChange={event => handleChange(event, { setFieldValue })}
            onBlur={event => handleBlur(event, { setFieldTouched })}
          />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  );
}

In this example, the handleChange and handleBlur callback functions are created using the useCallback hook, and they are passed the setFieldValue and setFieldTouched functions as arguments, respectively. This ensures that the callback functions are only recreated if the setFieldValue or setFieldTouched functions change, minimizing the impact of re-renders on the component.

Keep in mind that using the useCallback hook can have a performance benefit only if the callback function has expensive operations or if the component re-renders frequently. If the callback function is simple and the component does not re-render frequently, using the useCallback hook may not have a significant impact on performance.

add setInitialValues to useFormikContext and setInitialValue to useField

 

In Formik, the setInitialValues function can be used to set the initial values of the form, and the setInitialValue function can be used to set the initial value of a specific field in the form. These functions are available as part of the useFormikContext and useField hooks, respectively.

Here is an example of how you can use the setInitialValues and setInitialValue functions to set the initial values of a form:

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

function MyForm() {
  const { setInitialValues } = useFormikContext();
  const [field, { setInitialValue }] = useField('number');

  useEffect(() => {
    setInitialValues({
      number: '',
      text: '',
    });
  }, [setInitialValues]);

  useEffect(() => {
    setInitialValue(123);
  }, [setInitialValue]);

  return (
    <Form>
      <Field type="number" name="number" />
      <Field type="text" name="text" />
      <button type="submit">Submit</button>
    </Form>
  );
}

In this example, the setInitialValues function is used to set the initial values of the form to an empty string for the number field and an empty string for the text field. The setInitialValue function is used to set the initial value of the number field to 123.

Keep in mind that the setInitialValues and setInitialValue functions should be called inside a useEffect hook to ensure that they are only called when the component mounts or when their dependencies change.

You can use the setInitialValues and setInitialValue functions to set the initial values of your form and individual fields as needed. For more information on using these functions, you can refer to the Formik documentation.

More issues from JaredPalmer repos

 

Troubleshooting jaredpalmer-tsdx

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.