0

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

23
  • show the code where you get the error. where you have the console.log Commented Dec 10, 2020 at 17:01
  • Ok, i'll do that, just a minute Commented Dec 10, 2020 at 17:02
  • 1
    Then perform the check on the length? if(Object.keys(companyData).length !== 0) Commented Dec 10, 2020 at 17:40
  • 1
    @EmileBergeron Yep, I've checked this question and that what i really want! Thanks a lot Commented Dec 10, 2020 at 17:51
  • 1
    @EmileBergeron when you said that: Wouldn't it be 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 the data object Commented Dec 10, 2020 at 18:44

2 Answers 2

3

When your component is rendered at first, you will have empty object as your companyData, as you provide {} in useState(). Your object will not be empty only after request completes.

So your console.log at first render is actually {}.date1.CashFlow - undefined error. Either use a flag to understand that data arrived, or provide some default non-empty object for your state in useState

Sign up to request clarification or add additional context in comments.

4 Comments

Yes Exactly! Thanks, I dealt with this by providing a default object for my state called isloaded and if the data is loaded then the value for this state will be true, according to this question
another way i did it, by checking the length for the Object
but can you explain to me, what do you mean when you said flag
Flag usually is some Boolean variable, isLoaded - is exactly what I meant and what I called flag
2

It's because the useEffect() mocks Componentdidmount and Componentwillupdate which means that when you try to console log the data outside the useEffect the data is actually is not loaded yet. use this code to see the data;

if(data){
//  your logic
}

and use states to store the data as nikita suggested in her answer

2 Comments

Thanks a lot you and nikita, I dealt with this by providing a default object for my state called isloaded and if the data is loaded then the value for this state will be true, according to this question
another way i did it, by checking the length for the Object

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.