Home > front end >  How do I resolve Cannot read properties of undefined (reading 'Fiscal Year')?
How do I resolve Cannot read properties of undefined (reading 'Fiscal Year')?

Time:07-09

I am accessing the data retrieved using an API and I am displaying it like this.

<Grid ><Typography variant="body1">Fiscal Year </Typography></Grid>
<TableContainer style={{width:600,height:170}}> 
{stats?<Table 
sx={{alignItems: "center",
display:""}}
>
{stats['Financial Highlights']['Fiscal Year']?<TableBody>
                             <TableRow hover>
                                 <TableCell align="left"> Fiscal Year Ends</TableCell>
                                 <TableCell align="right">  {stats['Financial Highlights']['Fiscal Year']['Fiscal Year Ends']===null?"N/A":stats['Financial Highlights']['Fiscal Year']['Fiscal Year Ends']}</TableCell>
                             </TableRow>
                             <TableRow hover>
                                 <TableCell align="left"> Most Recent Quarter (mrq)</TableCell>
                                 <TableCell align="right">{stats['Financial Highlights']['Fiscal Year']['Most Recent Quarter (mrq)']===null?"N/A":stats['Financial Highlights']['Fiscal Year']['Most Recent Quarter (mrq)']}</TableCell>
                             </TableRow>
</TableBody>:"Loading"}
</Table> :<div>Loading...</div>}                        
</TableContainer>

But I keep getting "Uncaught TypeError: Cannot read properties of undefined (reading 'Fiscal Year')" despite proper data existing. On doing console.log I can see this. enter image description here

Any help is appreciated.

CodePudding user response:

I could be wrong but I believe by the time compiler enters stats['Financial Highlights']['Fiscal Year'], your API is still busy fetching the response. I would suggest you add a nullable operator like this

stats?.['Financial Highlights']?.['Fiscal Year']

It will pass this check and render the accurate result once the HTTP call get some data to show.

  • Related