Reputation: 537
I have a React element to which I send
<Element first={this.props.first} list1={this.state.list1} list2={this.state.list2} />
Both list1
and list2
are set by methods called in componentDidMount()
as they are get requests.
And I am defining and using Element
like this with list2
and here the logged list2
is empty.
const Element = (props) => (
<div className='a'>
{console.log('something' + JSON.stringify(props.list2))}
<Link className='class' to={props.list2.find(o => o.name === props.first.name).dead === true
? ('/abc/' + (props.first.a ? props.first.a : '')) : ''}>
{props.first.a ? <i>{props.first.b}</i> : 'Do'}
</Link>
</div>
)
Output here is:
something []
and then
Uncaught TypeError: Cannot read property 'dead' of undefined
But if I don't use the value of list2
then it prints the correct list on logging. I mean, for code like this the logged data is correct and non-empty:
const Element = (props) => (
<div className='a'>
{console.log('something' + JSON.stringify(props.list2))}
<Link className='class' to={true ? ('/abc/' + (props.first.a ? props.first.a : '')) : ''}>
{props.first.a ? <i>{props.first.b}</i> : 'Do'}
</Link>
</div>
)
Output here is:
something [{"name":"a", "dead":true}, {"name":"b", "dead":false}]
And output for props.first.name is:
"a"
I am not able to understand why is this happening. I would appreciate any help.
Upvotes: 0
Views: 169
Reputation: 1075159
Most likely, the first time Element
is rendered, props.list2
is empty (or at least doesn't contain a match for props.exam.id
), but then it's rerendered by the parent component with a non-emtpty list / list with a matching entry. Your code doesn't check that props.list2.find
found something before trying to use its dead
property, which will blow up if find
didn't find anything (for instance, because the list was empty). There should be an error in the web console about trying to use the property dead
of undefined
. find
returns undefined
if it doesn't find anything.
You'll need to either:
Update the logic in Element
to allow for the possibility props.list2.find
won't find anything; or
Update the parent element so it doesn't render Element
with a list where props.list2.find
won't find anything (but that argues for refactoring so the parent passes what you're looking for into Element
, rather than having Element
try to find it).
Upvotes: 1