Ad

Simply Rendering Data From Api

- 1 answer

i'm trying my hardest to wrap my head around this concept and after wasting a couple hours i figured id try and see if someone would kindly fix and elaborate upon such a simple matter

  constructor(props) {
    super(props);
    this.state = {
        marketdata: [],
        loading: true
    }
  }


componentDidMount() {
    axios.get('https://api.coingecko.com/api/v3/global')
    .then(res => res.data)
    .then((data) => {
      this.setState({ marketdata: data })
      console.log(this.state.marketdata.data.market_cap_change_percentage_24h_usd)
     })
}

...

render() {

    const { coindata, marketdata} = this.state;

    <p>{marketdata.data.market_cap_change_percentage_24h_usd}</p>

TypeError: Cannot read property 'market_cap_change_percentage_24h_usd' of undefined

i want to be able to better understand so i can carry on and not get stuck when trying to consume data from APIs throughout this entire project.

Ad

Answer

Not entirely sure what this.setState() does, but I assume it should set the member state.

The problem is that you try to access a member of an object while that object does not exist. So, you should change

this.state.marketdata.data.market_cap_change_percentage_24h_usd

to

this.state.marketdata.market_cap_change_percentage_24h_usd

{ marketdata: data } does not mean that the new property is marketdata.data but the colon (:) is an assignment just like =, so marketdata gets the value of data.

If that does not work try to console.log from "up to bottom" which means first log this.state , then this.state.marketdata and so on, until you see what you received and set.

Ad
source: stackoverflow.com
Ad