Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

reactjs - Handle Undefined Object Using JavaScript Find

I have two teams in an array which have id 1 and 2:

{
   "teams": [
            {
                "id": 1,
                "name": "England",
                "groupName": 4
            },
            {
                "id": 2,
                "name": "Germany",
                "groupName": 6
            }
    ]
}

I have to make an API call to the backend which sometimes returns an id of 0 (which is not mapped in the array above). Here is the JSX code when I try to render it to a Table:

                        <td style={{ width: '16.66%', wordBreak: 'break-all' }}>
                            {teams.find((team) => team.id === fixture.team1Id).name}
                        </td>

As a result, I get a TypeError: Cannot read property 'name' of undefined when fixture.team1Id is 0. How can I handle it on the front-end to return a string like "TBC" whenever fixture.team1Id is 0?

question from:https://stackoverflow.com/questions/65641469/handle-undefined-object-using-javascript-find

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

find method will have undefined when nothing found.
Use ?. optional chaining operator and ?? nullish coalesce operator.

{teams.find((team) => team.id === fixture.team1Id)?.name ?? 'TBC'}

Update: When dont have support for these operators

const found = teams.find((team) => team.id === fixture.team1Id);

{found ? found.name : 'TBC'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...