Home > Enterprise >  'Cannot destructure property of as it is undefined' during map
'Cannot destructure property of as it is undefined' during map

Time:03-13

I was trying to make an array.map that retans an object. Some objects have a key "last_paper" and others don't. I need to pass through all the properties of this object and send them to other React component. But, not all objetcs have the key "last_paper", so when it pass through the array, my page breaks and send me this error 'Cannot destructure property of as it is undefined'. I know that the reason of the error message is the lack of the key "last_paper" in some objects but I don't know how to avoid this problem.

My component RobotContainer, robots is my array with objects.

{robots.map((robot) => <RobotCard key={robot.id} robot={robot} />)}

in my component RobotCard i try do destruct some robot props, including the last_paper. last_paper is an object too and I need some infos from this too.

const { id, title, last_paper } = robot;
const { paper } = last_paper;

still in RobotCard i try to render paper:

<h1>
{paper}
</h1>

But some of robot don't have the key last_paper i get the error in the title. If i don't have the last_paper property I just wanna render another div for example. Can you help me solving this problem?

CodePudding user response:

Don't try to destructure something that might not exist. Sounds like you need to use conditional rendering - render the <h1> if the property exists, and otherwise render that "another div", in whatever format you're looking for.

const { id, title, last_paper } = robot;
// ...

{
  last_paper
    ? <h1>{last_paper.paper}</h1>
    : <div>No paper</div>
}

If rendering an empty h1 in such a situation would work, you could also do just

const { id, title, last_paper } = robot;
// ...

<h1>{last_paper?.paper}</h1>

CodePudding user response:

Some option would be to provide a default value to last_paper when destructuring it:

const { paper } = last_paper ?? { paper: 'Some default value' };

or

const { paper } = last_paper ?? {} // Would default to undefined
  • Related