How to properly use Formik’s setStatus method?

Sometimes, we want to properly use Formik’s setStatus method.

In this article, we’ll look at how to properly use Formik’s setStatus method.

How to properly use Formik’s setStatus method?

To properly use Formik’s setStatus method, we can call it in the submit handler.

For instance, we write:

import React from "react";
import { Formik } from "formik";

export default function App() {
  return (
    <Formik
      initialValues={{ email: "", password: "" }}
      validate={(values) => {
        const errors = {};
        if (!values.email) {
          errors.email = "Required";
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$/i.test(values.email)
        ) {
          errors.email = "Invalid email address";
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting, setStatus }) => {
        setStatus();
        setTimeout(() => {
          console.log(JSON.stringify(values, null, 2));
          setSubmitting(false);
          setStatus("success");
        }, 1000);
      }}
    >
      {({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
        status
      }) => (
        <form onSubmit={handleSubmit}>
          {status}
          <input
            type="email"
            name="email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.email}
          />
          {errors.email && touched.email && errors.email}
          <input
            type="password"
            name="password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.password}
          />
          {errors.password && touched.password && errors.password}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </form>
      )}
    </Formik>
  );
}

We have a form that we create with the Formik component.

We have the validate prop set to a function that returns any errors in the input values.

The onSubmit prop is set to a function that calls setStatus to set the status property in the render prop’s object parameter.

We display status above the inputs.

The values property has the input values of each field.

We set the name attribute of each input to set the properties with the names of the names attributes of the values object to the input value of the field with the given name attribute.

Now when the onSubmit function is run, we should see ‘success’ displayed on the left of the form.

Conclusion

To properly use Formik’s setStatus method, we can call it in the submit handler.