Search code examples
node.jsreactjsmongodbexpressmern

TypeError: Cannot read properties of undefined (reading 'name') reactjs


frontend code:

{

(opp||[]).map(opps=>{
    return(
        <div className="card OppCard">
        <div className="card-body" >
            <h4>{opps.title}</h4>
            <p><b>Author : {opps.postedBy.name}</b></p>
            <p style={{ "margin": "0px" }}>Description : {opps.desc}</p>
            <p style={{ "margin": "0px" }}>Location : {opps.location}</p>
            <p style={{ "margin": "0px" }}>Experience Required : {opps.experience}</p>
            <p style={{ "margin": "0px" }}>Last Date to Apply : {opps.ld}</p>
        </div>
    </div>
    )
}) 
}

At <p><b>Author : {opps.postedBy.name}</b></p> this line error occurs here is a pic attached for opps object: opps is the object and postedBy is also an object, how should I access opps.postedBy.name????


Solution

  • whenever you try to access json object, check if it is undefined or not beffore calling method or accessing properrty replace this line,

    <p><b>Author : {opps.postedBy.name}</b></p>
    

    with this, instead, this will work because you are checking before accessing it, also when you try to .filter() or .map() first check if it is empty or not, if not empty then only call, else it will throw error

    <p><b>Author : {opps.postedBy && opps.postedBy.name}</b></p>