Upon mapping my searchResults array that gets populated with objects (being returned via elastic search) of my Drug object into my React component, I ran into an issue when testing for a case of an erroneous result with a missing key in my object. The app understandably crashes with the "TypeError: Cannot read property 'icdCodeNum' of undefined" which in my case is due to the missing "primaryIcdCode" key in my Drug object. I am going through various conditional blocks to check for the missing data before mapping, but all my solutions end up blocking even correct search results from being returned.
A normal searchResult array response looks as follows (where all the necessary object keys exist):
[{"otherIcdCodes":[{"otherIcdCodes":[],"_id":"5bc8393936ca7a5008025a78","brandName":"Advil","genericName":"Ibupr
ofen","primaryIcdCode":{"_id":"5bc838e036ca7a5008025a75","icdCodeNum":"R52","icdCodeValue":"Pain, unspecified"},"dru
gNotes":"Don't take on empty stomach","drugClass":"Pain management","drugSchedule":"0","extraDrugInfo":"","date":"20
18-10-18T07:41:45.183Z","__v":0}]
The problem arises, when my search result object is missing the "primaryIcdCode" key from one of my search responses (due to incorrectly entered data in the database itself, which is the way I discovered the issue).
I am mapping my array as follows in my DrugSearch component:
<div>
<ListGroup>
{searchResults.map(
({
_id,
brandName,
genericName,
drugNotes,
primaryIcdCode,
otherIcdCodes
}) => (
<Card key={_id} body>
<h4>
<Button disabled className="drug-search-name">
{brandName} | {genericName}
</Button>
</h4>
<div>
<Button className="btn-lg-icd">
{primaryIcdCode.icdCodeNum}
</Button>
</Card>
)
)}
</ListGroup>
</div>
What would be the proper approach to catch the missing data before the mapping? I tried filtering, but I couldn't configure it properly with my DrugSearch component's logic, so my search results wouldn't even get returned.
Here is a link to the full component (check DrugSearch.js - ignore the index.js) to make more sense out of the issue:
https://codesandbox.io/s/m3p1k31p0j
Thanks in advance!
primaryIcdCodeproperty?