Home > Mobile >  Cannot read properties of undefined (reading 'name'): ReactJs
Cannot read properties of undefined (reading 'name'): ReactJs

Time:10-19

I have data in my console when I try to log it but I am not able to use it .

My data object looks like :

{_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '1234567890', work: 'singer', …}

accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxNmJmODJkMTZhMjk1MWU1M2YxMGRhNCIsImlhdCI6MTYzNDYyMDk3MiwiZXhwIjoxNjM1MDUyOTcyfQ.b9NZB-ogrdu_SulT1xJ8h62aHdyAo2jzTny2qakeaHY"

cpassword: "$2a$12$BZ17rY63qrq.Fw9wC29A.eabcuAHSY0mXfxSvcpxOFGfUeW4NUkMO"

email: "[email protected]"

name: "abd"

phone: "1234567890"

tokens: (3) [{…}, {…}, {…}]

work: "singer"

__v: 3

_id: "616bf82d16a2951e53f10da4"

[[Prototype]]: Object

import "./about.css"
import {useHistory} from "react-router-dom"


export default function About() {
    const history=useHistory();
    const [userData,setUserData]=useState();
    const callAboutPage=async()=>{
        try {
            const res=await fetch("/about",{
                method:"GET",
                headers:{
                    Accept:"application/json",
                    "Content-Type":"application/json"
                },
                credentials:"include"
            })
            const data=await res.json();
            console.log(data);
            setUserData(data);

            if(!res.status===200){
               const error=new Error (res.error)
               throw error
            }
            
        } catch (error) {
            console.log(error)
            history.push("/login")
        }
    }
    
  useEffect(() => {
     callAboutPage();
  }, [])

    return (
        <div className="abt-body">
            <div className=" d-flex justify-content-center align-items-center about">
                
                Name:{userData.name}
                <br />
                Id:{userData._id}
                <br />
                Email:{userData.email}
                <br />
                Phone:{userData.phone}
                <br />
                Work:{userData.work}
             
                

                

            </div>
           

                <div class="card-footer text-muted d-flex justify-content-center align-items-center">
    Designed and Developed by : Harsh Raj Ambastha
  </div>
        </div>
    )
}

CodePudding user response:

You might try using Javascript optional chaining: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Try adding the operator to each of your fields:

userData?.name
userData?._id

etc.

CodePudding user response:

It is because you set initial value as empty which will be interpreted as primitive value. So when it renders initially it finds you are trying to access a property of a primitive value which ain't there. Give initial value as an empty object, it will then no longer throw an error here. useState({})

  • Related