Home > OS >  Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj'
Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj'

Time:06-12

const navigate = useNavigate();

const responseGoogle = (response) => {

  localStorage.setItem('user', JSON.stringify(response.profileObj));

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

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

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

I get an error that "name is undefined" – but how? What's the problem with name? I've been dealing with this for a long time and I still can't figure it out

CodePudding user response:

Google response has 3 responses types. On success response : GoogleLoginResponse | GoogleLoginResponseOffline, on failure response : error.

profileObj exist only on the GoogleLoginResponse type. So, if you have an other reponse type, profileObj will be undefined, and you can't destructure the name.

You have to manage it.

export interface GoogleLoginProps {
  readonly onSuccess?: (response: GoogleLoginResponse | GoogleLoginResponseOffline) => void,
  readonly onFailure?: (error: any) => void,
  //...
}
// Based on https://developers.google.com/identity/sign-in/web/reference
export interface GoogleLoginResponse {
  getBasicProfile(): BasicProfile;
  getAuthResponse(includeAuthorizationData?: boolean): AuthResponse;
  reloadAuthResponse(): Promise<AuthResponse>;
  getGrantedScopes(): string;
  getHostedDomain(): string;
  getId(): string;
  isSignedIn(): boolean;
  hasGrantedScopes(scopes: string): boolean;
  disconnect(): void;
  grantOfflineAccess(options: GrantOfflineAccessOptions): Promise<GoogleLoginResponseOffline>;
  signIn(options: SignInOptions): Promise<any>;
  grant(options: SignInOptions): Promise<any>;
  // google-login.js sez: offer renamed response keys to names that match use
  googleId: string;
  tokenObj: AuthResponse;
  tokenId: string;
  accessToken: string;
  readonly code?: string;//does not exist but here to satisfy typescript compatibility
  profileObj: {
    googleId: string;
    imageUrl: string;
    email: string;
    name: string;
    givenName: string;
    familyName: string;
  }
}
export interface GoogleLoginResponseOffline {
  readonly code: string;
}

CodePudding user response:

Piggy backing off of o.c answer:

Google response has 3 responses types: GoogleLoginResponse, GoogleLoginResponseOffline, or error. Only GoogleLoginResponse has the profileObj property.

Perhaps changing the below line:

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

To the below would help avoid the crash:

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

Your still going to need to address the underlying issue in other ways. But null-coalescing would stop the crash.

  • Related