Home > Software design >  Cannot destructure property 'name' of 'response.profileObj'
Cannot destructure property 'name' of 'response.profileObj'

Time:10-20

I faced with a problem while I was coding about Google sign-in line. I wrote these lines:

const Login = () => {
  const navigate = useNavigate();
  const responseGoogle = (response) => {
    localStorage.setItem('user', JSON.stringify(response.profileObj))

    const { name, googleId, imageUrl } = response.profileObj;

    const doc = {
      _id: response.profileObj.googleId,
      _type: 'user',
      userName: response.profileObj.name,
      image: response.profileObj.imageUrl,
    }

    client.createIfNotExists(doc)
      .then(() => {
        navigate('/', { replace: true })
      });
  }

But when I am looking through console log, I see there is appearing

Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj' as it is undefined.

So what kind of solutions do you offer for me? Btw also these code should direct me to the main page after log in with my email but it also doesn't work.

CodePudding user response:

You can add a null check like this.

const Login = () => {
  const navigate = useNavigate();
  const responseGoogle = (response) => {
    localStorage.setItem("user", JSON.stringify(response.profileObj));
    if (response.profileObj) {
      const { name, googleId, imageUrl } = response.profileObj;

      const doc = {
        _id: response.profileObj.googleId,
        _type: "user",
        userName: response.profileObj.name,
        image: response.profileObj.imageUrl,
      };

      client.createIfNotExists(doc).then(() => {
        navigate("/", { replace: true });
      });
    }
  };
};

Else if you provide type of the profileObj it wont throw that error

CodePudding user response:

Your response.profileObj seems to be undefined Are you sure you passed the profileObj property in the response object?

  • Related