Formik and Yup : TypeError: Cannot read property 'object' of undefined
Asked Answered
L

4

20

I am new to React and was trying out formik with yup for the validation. I am currently getting the error below:

TypeError: Cannot read property 'object' of undefined

with this code:

validationSchema: Yup.object().shape({
  firstName: Yup.string().required()
}),

I am using all the latest versions of formik,react and yup. The versions are

"yup": "^0.25.1" "formik": "^0.11.11", "react": "^16.4.0", "react-dom": "^16.4.0",

Could some one help me to resolve this issue?

It is replicated here https://codesandbox.io/s/lrowpj8pq7

Thanks!

Laminated answered 8/6, 2018 at 5:20 Comment(3)
provide code where you are getting the errorHoebart
I have added sample codeLaminated
Shawn, please change the correct answer.Otila
B
135

The correct answer is not to downgrade, but to change how you import it.

Try import * as Yup from 'yup' instead of import Yup from 'yup'.

// wrong
import Yup from 'yup';

// correct
import * as Yup from 'yup';

Here is your example working: https://codesandbox.io/s/xlnw2x0kk4.

Bodega answered 13/6, 2018 at 7:46 Comment(6)
It was breaking for me and this answer helped without downgrading! Thanks.Dockery
@Panos Bechlivanos just curios. why this matters?Toor
@Ezeewei it matters because in javascript there are many variations in how you will export your modules eg. in this example they changed how they exported their modules from exporting a big object that contained every function, to exporting every function separately as a named export.Bodega
import * as Yup from 'yup'; using this still getting same error ^0.27.0Exhilarative
This did not work on on march 2021. Maybe it is not valid on newer version. Need new solution.Corduroy
Worked for me too. How bizarre though. I expect these to be semantically the same.Macur
C
1

I had the same problem and then I realised I was using yup in the code instead of Yup. Below is the code sample and it works perfectly :)

import * as Yup from "yup";

const formSchema = Yup.object().shape({
  email: Yup.string().required().email(),
  password: Yup.string().required().min(6),
});
Columbuscolumbyne answered 2/6, 2021 at 20:19 Comment(0)
H
0

in my case I forgot to export validationSchema function, and access in other file which makes to cause undefined for erros.userName

Huberthuberto answered 20/9, 2021 at 10:31 Comment(0)
C
0

For me registering desired field helped:

{...register('birthDate')}
Charmeuse answered 6/10, 2023 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.