Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 352
Shawn Avatar asked Jun 08 '18 05:06

Shawn


People also ask

What is cannot read property of undefined in JavaScript?

The TypeError: Cannot read property of undefined is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable. TypeError: Cannot read properties of undefined (reading x) Undefined means that a variable has been declared but has not been assigned a value.

Why can’t I call a function on an undefined variable?

In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.

What is the meaning of undefined in JavaScript?

Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.

How do I fix the Yup import error in typescript?

If you’re using TypeScript with Yup, you might be running into this error: import yup from 'yup'; const schema = yup.object ().shape ( {}); To fix the error message above, make sure you have types for Yup installed.


2 Answers

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.

like image 132
Panos Bechlivanos Avatar answered Oct 17 '22 16:10

Panos Bechlivanos


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),
});
like image 1
ranjit kumar Patel Avatar answered Oct 17 '22 14:10

ranjit kumar Patel