In this.state.companiesIncome, I have an array of 50 objects that have a {value and date}, but when I'm trying to console.log(this.state.companiesIncome[2].value) I'm receiving TypeError: Cannot read property '2' of null.
What I'm doing wrong?
import React, { Component } from 'react'
import './CompanyTotalIncome.css'
import axios from 'axios'
class CompanyIncome extends Component {
constructor(props) {
super(props)
this.state = {
companyID: props.companyID,
companiesIncome: null
}
}
componentWillMount() {
axios.get(`https://API/${this.state.companyID}`).then(res => {
this.setState({ companiesIncome: res.data.incomes })
})
}
render() {
console.log(this.state.companiesIncome[2].value)
return (
<>
<th>Total income</th>
</>
)
}
}
export default CompanyIncome
componentWillMountis a lifecycle method that will get called when your component mounts, however, your API call is asynchronous, so by the time you get torender, yourAPImay still be going and yourstateisnull, so you need to handle this better, for example render a list of items onlyif (this.state.companiesIncome && this.state.companiesIncome.length > 0)