1

Trying to show the length of the data that is received from api response.but it say cannot read property of undefined


async  componentDidMount() {
        Users.getAppAuthUser(1,true).then((res)=>{
            this.setState({data:res});
            this.setState({loading:false});
        })
        console.log(this.state.data);

}
render() {
    return (
         <div >                    
            <span >({  this.state.data ===[] ?    0 :  this.state.data.accounts.length })
            </span>
        </div>
    )
}
1
  • Your first render is happening even before data is loading from promise. You can safeguard it by checking if this.state.data exists. Commented Sep 19, 2019 at 4:44

3 Answers 3

2

I think what you can do is

<div>
{ this.state.data && <span> {{this.state.data.length}} </span> }
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Sometimes it could happen because while the rendering is processing, the state is not done yet so it won't get the whole properties of the keys inside the state. In this case it hasn't finished loading data so length is not available.

async before componentDidMount is not valid here.

state = {
  data: [], loading: false
}

componentDidMount() {
    Users.getAppAuthUser(1, true).then((res)=> ({
        this.setState({data: res, loading:false});
    }))
}

render() {
    return (
        <div>                    
            {this.state.data && <span>{this.state.data.accounts.length}</span>}
        </div>
    )
}

If this line doesn't work {this.state.data && <span>{this.state.data.accounts.length}</span>} do this instead:

{this.state.data && this.state.data.accounts && <span>{this.state.data.accounts.length}</span>}

If you using lodash you may import get:

import get from 'lodash.get';

...

<div>                    
  <span>{get(this.state, 'data.accounts.length', null)}</span>
</div>

Comments

0

The reason to why u r getting undefined is not proper usage of async/await. Read to get more info bro

    async componentDidMount() {
        const response = await fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`);
        const json = await response.json();
        this.setState({ data: json });
    }

You should use it like this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.