简体   繁体   中英

How to guard against an undefined API call value in JSX?

I have a component that makes an API call and returns some financial data set as state like so:

      const [statisticsData, setStatisticsData] = useState({});

which works perfectly, however, the API does not always have all of the data I need to display. A basic example of the JSX attempting to be rendered:

    <StatBox
        statType="PE Ratio"
        statValue={statisticsData.summaryDetail.PERatio.fmt}
      />

The component renders perfectly when the PE Ratio is defined by the API call, however the API does not always produce a PE ratio. I have tried using a ternary operator to check if statisticsData.summaryDetail.PERatio.fmt is defined, which did not work. I'm also not even able to get the typeof statisticsData.summaryDetail.PERatio.fmt as it throws a runtime error saying

'TypeError: Cannot read property 'fmt' of undefined'.

How can I guard against undefined values if the undefined value throws a runtime error before I can even check if it's undefined?

In this case refactor the component like bellow

<StatBox
    statType="PE Ratio"
    statValue={statisticsData?.summaryDetail?.PERatio?.fmt ?? null}
/>

?? is an operator that identify if the left hand side is undefined and then returns the right hand side. So the the fmt or PERatio is not defined it will pass null . Now handle the null value inside the component accordingly or pass any default value if you want.

<StatBox
    statType="PE Ratio"
    statValue={statisticsData?.summaryDetail?.PERatio?.fmt}
/>

? operator checks if the value exists then it goes inside the object otherwise return undefined there is no need for?? null

in your example statisticsData?.summaryDetail if 'statisticsData' is null then it wont go to 'summaryDetail' if it exists then it will go 'PERatio' and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM