'Issue when retrieving data from an API in react and node js : TypeError: Cannot read properties of undefined (reading '0')

I cant seem to figure a way around this following error : TypeError: Cannot read properties of undefined (reading '0'). So I am calling an external API to receive financial data. From that retrieved data I call certain values and by calling the index of of where those values are stored for example api.annualReports[0].operatingCashflow. However, the odd things is that I am able to receive and have the data formatted the way I like to but most of the time it I would get the error I mentioned above.


Here one the approach I took:

const formatedFinancialData =  asyncHandler  (async(req, res) => {
      const { ticker } = req.body
       if(ticker){
          const formattedDate = {} 
          const cashFlow =  `https://www.alphavantage.co/queryfunction=CASH_FLOW&symbol=${ticker}&apikey=${process.env};
          const cashFlow_reponse = await fetch(cashFlow);
          const cashFlow_Json = await cashFlow_reponse.json()
    
          formattedDate.cashFlow_2021 = (cashFlow_Json.annualReports[0].operatingCashflow);
          formattedDate.cashFlow_2020 =(cashFlow_Json.annualReports[1].operatingCashflow)'
          formattedDate.cashFlow_2019 = (cashFlow_Json.annualReports[2].operatingCashflow)
    
       }
 }

After looking around for another approach I tried using axios and I encountered the same issue. Here the code for that approach...

 async function CashFlowData() {
   return await axios.get(`https://www.alphavantage.co/query?function=CASH_FLOW&symbol=${ticker}&apikey=${process.env.ALPHA_API_TOKEN}`);
}
  
try {
  const response = await CashFlowData();
  if(response.data.annualReports){
     formattedDate.cashFlow_2021 = (response.data.annualReports[0].operatingCashflow);
   }
 }

I ran into the same issue most of time I am able to receive and format the data and the other times I would get this error TypeError: Cannot read properties of undefined (reading '0').

In the front end I take in the ticker from the user and pass is along and here's example code:

const [tickerData, setTickerData] = useState([]);
const keyPress =  async (e) => {
    if(e.keyCode === 13 || e.key === 'Enter' ){
      
      e.preventDefault();
      const data = e.target.value;
      await axios.post('http://localhost:5000/api/apiData',{
        ticker: data
      }).then( res => {  
        setTickerData( res.data.formattedDate)
      }).catch((err) => {
        setErrorMsg(`${err.message} - Please try again!`)
      })
    }    
  }

I cant seem to find a way around it for quite some time now and honestly, I would really appreciate any help thank you.



Solution 1:[1]

There's a huge possibility that annualReports is not an array or is an empty array which means we can't access the first(0) object in the array hence the error: TypeError: Cannot read properties of undefined (reading '0').

Use optional chaining to avoid the error if annualReports will not always be an array or if annualReports[0] might be undefined.

Example: cashFlow_Json.annualReports[0]?.operatingCashflow

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1