Accessing Formik's setValues in useEffect

Viewed 2252

I have a Formik form that needs to respond to an error useContext. I have no idea how to access Formik's props outside the Form. I'll just post the code here, and I'd appreciate any advice.

  const authContext = useContext(AuthContext);
  const { login, error, isAuth } = authContext;

  useEffect(
    () => {
      if (isAuth) {
        props.history.push("/");
      }

      if (error) {
        // access Formik's setValues
      }
    },
    // eslint-disable-next-line
    [isAuth, error, props.history]
  );

<Formik
            initialValues={{
              username: "",
              email: "",
              password: "",
              password2: "",
            }}
            validationSchema={Yup.object({
              email: Yup.string()
                .email("Invalid email address.")
                .required("An email is required."),
              password: Yup.string().required("A password is required."),
            })}
            onSubmit={(submissionData, { setSubmitting }) => {
                setSubmitting(true);
                login(submissionData);
                setSubmitting(false);
            }}
          >
            {(props) => (
              <Form>
                <MyInput
                  label="Email: "
                  name="email"
                  type="email"
                  placeholder="Enter your email address"
                />
                <MyInput
                  label="Password: "
                  name="password"
                  type="password"
                  placeholder="Enter your password"
                />
                <button type="submit" className="btn">
                  {props.isSubmitting ? (
                    <ClipLoader size={16} color={"color"} />
                  ) : (
                    "Submit"
                  )}
                </button>
              </Form>
            )}
          </Formik>

Thank you in advance.

1 Answers

You could use useFormik hook to access the setValues.

You could check the docs here

Example:-

 import React from 'react';
 import { useFormik } from 'formik';

 export default function App() {
  const formik = useFormik({
     initialValues: {
       firstName: '',
       lastName: '',
       email: '',
     },
     onSubmit: values => {
       alert(JSON.stringify(values, null, 2));
     },
   });

   React.useEffect(() => {
     console.log(formik.setValues);
   }, []);

   return null;
 }
Related