Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik | error useFormikContext formik values undefined

I have the following code:

const {
     values,
     handleChange,
     setFieldValue,
     handleSubmit,
     isSubmitting,
     isValid 
} = useFormikContext();

And i have the formik form inside a const comp

const Body = () => {
 ...
 return(
 <Formik
   ....
   ....>
   {props=>{

     <Form>
       ... then some fields here... etc
       ...
       ...
     </Form>

    }}

 </Formik>
}

It gives me this error:

TypeError: Cannot destructure property 'values' of 'Object(...)(...)' as it is undefined.

I've also checked this question: Formik 2.0.1 useFormikContext formik values undefined

however it didnt work even writing useFormikContext() inside Body

like image 953
olscode Avatar asked Nov 19 '20 14:11

olscode


1 Answers

This hook will only work if there is a parent Formik React Context from which it can pull from.

Source

Make sure you are using useFormikContext in a descendant of <Formik> Something like this:

<Formik>
  <Form>
    <MyApp />
  </Form>
</Formik>
// MyApp.jsx

const MyApp = () => {
  const formik = useFormikContext();

  // do what you want with formik
}
like image 168
Antonio Erdeljac Avatar answered Sep 19 '22 11:09

Antonio Erdeljac