Reputation: 3
export default function Detail(props){
return(
<Modal {...props}>
<Modal.Header closeButton style={{ backgroundColor: '#6595FC', color:'white' }}>
<Modal.Title style={{ wordBreak: 'break-all' }}>
{props.jobname} Details
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Container>
<Row>
{props.detailData.detailData ? props.detailData.detailData[0].WORKFLOW_NAME : ''}
{props.detailData.detailData ? props.detailData.detailData[0].SQL_ID : ''}
</Row>
</Container>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" style={{ backgroundColor: '#6595FC' }}>Restart</Button>
</Modal.Footer>
</Modal>
)
}
When there is data it works perfectly fine but when there is no data, it gives me the error
TypeError: Cannot read property 'WORKFLOW_NAME' of undefined
props.detailData.detailData ? props.detailData.detailData[0].WORKFLOW_NAME : ' ' isnt this suppose to work like a null & empty check?
Upvotes: 0
Views: 38
Reputation: 150
David's answer is perfect. But you also can do this:
props.detailData?.detailData[0]?.WORKFLOW_NAME || ''
Upvotes: 0
Reputation: 218808
You're only checking if props.detailData.detailData
itself is "truthy" (it exists). An empty array exists and passes this check, but it has no element at position 0
so the attempt to dereference that element will result in an error.
You can also add a length check:
(props.detailData.detailData && props.detailData.detailData.length > 0) ? props.detailData.detailData[0].WORKFLOW_NAME : ''
If you need to defend against other kinds of bad data you might also add an isArray()
check, but that may be overkill.
Upvotes: 1