Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj" - Solution #21

Open
Achilleaus opened this issue Aug 8, 2022 · 7 comments

Comments

@Achilleaus
Copy link

Achilleaus commented Aug 8, 2022

Solution for errors such as: "Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj' as it is undefined."
and sanity database not updating or redirects to home failing.

Here's how I solved it:

  1. Install the latest Google OAuth Package: npm install @react-oauth/google and get your client ID as shown in JSM's video.
  2. Install the dependency jwt-decode: npm install jwt-decode. This is to decode the jwt_token that the google oauth returns.
  3. Replace your login.jsx with the following:
import React from 'react';
import {GoogleLogin, GoogleOAuthProvider} from '@react-oauth/google';
import { useNavigate } from 'react-router-dom';
import shareVideo from '../assets/share.mp4';
import logo from '../assets/logowhite.png';
import { client } from '../client';
import jwt_decode from 'jwt-decode'

const Login = () => {
    const navigate = useNavigate();

    const responseGoogle = (response) => {

        const userResponse = jwt_decode(response.credential);

        localStorage.setItem('user', JSON.stringify(userResponse));
        const { name, sub, picture } = userResponse;

        const doc = {
            _id: sub,
            _type: 'user',
            userName: name,
            image: picture
        }
        
        client.createIfNotExists(doc).then(()=>{
            navigate('/', {replace: true})
        });

    };

    return (
        <div className="flex justify-start items-center flex-col h-screen">
            <div className=" relative w-full h-full">
                <video
                    src={shareVideo}
                    type="video/mp4"
                    loop
                    controls={false}
                    muted
                    autoPlay
                    className="w-full h-full object-cover"
                />

                <div className="absolute flex flex-col justify-center items-center top-0 right-0 left-0 bottom-0    bg-blackOverlay">
                    <div className="p-5">
                        <img src={logo} width="130px" alt='logo' />
                    </div>

                    <GoogleOAuthProvider
                        clientId={`${process.env.REACT_APP_GOOGLE_OAUTH_CLIENT_ID}`} className="shadow-2xl">
                        <GoogleLogin
                            onSuccess={responseGoogle}
                            onFailure={responseGoogle}
                            cookiePolicy="single_host_origin"
                        />
                    </GoogleOAuthProvider>
                </div>
            </div>
        </div>
    );
};

export default Login;
  1. To solve the images not appearing issue, as well as redirecting issues, replace Home.jsx with this:
import React, { useState, useRef, useEffect } from 'react'
import { HiMenu } from 'react-icons/hi'
import { AiFillCloseCircle } from 'react-icons/ai'
import { Routes, Route, Link } from 'react-router-dom'
import { Sidebar, UserProfile } from '../components'
import { client } from '../client'
import logo from '../assets/logo.png'
import Pins from './Pins'
import { userQuery } from '../utils/data'

const Home = () => {
  const [user, setUser] = useState(null)
  const [toggleSidebar, setToggleSidebar] = useState(false)
  
  const scrollRef = useRef(null);

  const userInfo = localStorage.getItem('user') !== 'undefined' ? JSON.parse(localStorage.getItem('user')) : localStorage.clear();

  useEffect(() => {
    const query = userQuery(userInfo?.sub);

    client.fetch(query).then((data) => {
      setUser(data[0]);
    })
    //eslint-disable-next-line
  }, []);

  useEffect(() => {
    scrollRef.current.scrollTo(0, 0);
  });

  return (
    <div className="flex bg-gray-50 md:flex-row flex-col h-screen transition-height duration-75 ease-out">
      <div className="hidden md:flex h-screen flex-initial">
        <Sidebar user={user && user} />
      </div>
      <div className="flex md:hidden flex-row">
        <div className="p-2 w-full flex flex-row justify-between items-center shadow-md">
          <HiMenu fontSize={40} className="cursor-pointer" onClick={() => setToggleSidebar(true)} />
          <Link to="/">
            <img src={logo} alt="logo" className="w-28" />
          </Link>
          <Link to={`user-profile/${user?._id}`}>
            <img src={user?.image} alt={user?.name} className="w-9 h-9 rounded-full " />
          </Link>
        </div>
        {toggleSidebar && (
          <div className="fixed w-4/5 bg-white h-screen overflow-y-auto shadow-md z-10 animate-slide-in">
            <div className="absolute w-full flex justify-end items-center p-2">
              <AiFillCloseCircle fontSize={30} className="cursor-pointer" onClick={() => setToggleSidebar(false)} />
            </div>
            <Sidebar closeToggle={setToggleSidebar} user={user && user} />
          </div>
        )}
      </div>
      <div className="pb-2 flex-1 h-screen overflow-y-scroll" ref={scrollRef}>
        <Routes>
          <Route path="/user-profile/:userId" element={<UserProfile />} />
          <Route path="/*" element={<Pins user={user && user} />} />
        </Routes>
      </div>
    </div>
  )
}

export default Home

Side Note: Don't forget to wrap your env variables in this: {`${MY-ENV-VARIABLE}`}

Also, this solves the problem for these two components (login and home), but for the other components, some changes will have to be made. I will post these changes as soon as I am done with the project.

@Achilleaus Achilleaus reopened this Aug 10, 2022
@Mansour-G
Copy link

Hello bro , i've implemented this code but am still getting this error can you please help me with it

Failed to load resource: the server responded with a status of 400

Screenshot 2022-08-27 165321

@Araragee
Copy link

Araragee commented Sep 3, 2022

thanks a bunch broooo

@CodeMuscle
Copy link

Amazing solution. Thanks a ton!

@Araragee
Copy link

Araragee commented Oct 22, 2022

image
image

help guys!!

@Prof-Software
Copy link

use googleLogout instead of "GoogleLogout"

@Nitisha47
Copy link

Hey, I tried your solution but I am getting this error. Can you just help me with it, Thank you
Screenshot (744)
.

@FatimahAs
Copy link

Hey, I tried your solution but I am getting this error. Can you just help me with it, Thank you Screenshot (744) .

change to

import { jwtDecode } from "jwt-decode";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants