First of all, I have useEffect() and it fetch data from API and pass it to React State called companyData
The API response looks like:
{
"data": [
{
"date1": {
"BalanceSheet": {
... {JSON DATA}
},
"CashFlow": {
... {JSON DATA}
},
"IncomeSheet": {
... {JSON DATA
}
]
}
And my useEffect and State looks like ..
const [companyData,setCompanyData] = useState({});
useEffect(()=>{
axios.get(`/api/company/view/${id}`).then((res)=>{
setCompanyData(res.data[0])
})
},[])
So when i am try to access companyData.date1.CashFlow ( outside useEffect )
Like this console.log(companyData.date1.CashFlow)
it returns TypeError: companyData.date1 is undefined
But if i try to console.log the companyData or companyData.date1
it returns the JSON without any errors
My React Component Code:
export default function YourAnalysis(props){
const [companyData,setCompanyData] = useState({});
const [tableToShow,setTableToShow] =
useState({incomesheet:false,balancesheet:false,cashflow:true});
const id = props.match.params.id
useEffect(()=>{
axios.get(`/api/company/view/${id}`).then((res)=>{
setCompanyData(res.data[0])
}).catch(err=>{
console.log('an error')
})
},[])
function renderTable(){
if(tableToShow.incomesheet){
return (<div></div>)
}
if(tableToShow.balancesheet){
return (<div></div>)
}
if(tableToShow.cashflow){
console.log(companyData) // works fine
console.log(companyData.date1.CashFlow) // date1 is undefined
}
}
I thought it's because the API response async and it takes time to assign\set data to companyData State,
the weird thing is that i can access and log the companyData or companyData.date1 i'll see the JSON data and everything is good
but when i try to access companyData.date1.CashFlow or companyData.date1.BalanceSheet or companyData.date1.IncomeSheetit returns undefined
maybe it because the name of date1?
or react has a method to deal with nested json object?
Any help? i am newbie in react
if(Object.keys(companyData).length !== 0)res.data.data[0]you're right in this point, but the API response that i show in my question it's the axios response but i removed the objects except thedataobject