0
votes

I am trying to pull data => Crypto Exchange rates. See API spec here: https://rapidapi.com/coingecko/api/coingecko?endpoint=apiendpoint_a6893c7b-2094-4a19-9761-0c0306fe741a but getting TypeError: Cannot read property 'map' of undefined

Error:

  32 | 
  33 | return (
> 34 |   <ul>
     | ^  35 |     { this.state.rates.map(i => <li>{i.data.rates}</li>)}
  36 |   </ul>
  37 | )

Code:

import React from 'react';
import './App.css';
import prettyFormat from 'pretty-format';
import axios from 'axios';

class App extends React.Component {

  state = {
    rates: []
    }

  componentDidMount() {

    axios({
      "method":"GET",
      "url":"https://coingecko.p.rapidapi.com/exchange_rates",
      "headers":{
      "content-type":"application/octet-stream",
      "x-rapidapi-host":"coingecko.p.rapidapi.com",
      "x-rapidapi-key":"f4756b8409msh762478a357cd070p10685fjsnce9080fa5478"
      }
      })
      .then((response)=>{
        console.log(response)
      })
      .then(rates => this.setState({ rates}))

  }

    render() {
      console.log(prettyFormat(this.state.data))

      return (
        <ul>
          { this.state.rates.map(i => <li>{i.data.rates}</li>)}
        </ul>
      )

    }
}

export default App;```
2

2 Answers

0
votes

As far as I can tell your processing of the response is incorrect. You chained two then statements. What you probably need is within the first then to access the rates data and set it as state:

  componentDidMount() {

    axios({
      "method":"GET",
      "url":"https://coingecko.p.rapidapi.com/exchange_rates",
      "headers":{
      "content-type":"application/octet-stream",
      "x-rapidapi-host":"coingecko.p.rapidapi.com",
      "x-rapidapi-key":"f4756b8409msh762478a357cd070p10685fjsnce9080fa5478"
      }
      })
      .then((response)=>{
        console.log(response)
        //response is an object with a data property that contains the rates
        const { rates } = response.data;
        this.setState({ rates }
      })
  }

I am not sure about the API you are using, but you should also consider taking care of a situation where response.data.rates is undefined. In the above code rates will equal to undefined and does not have a map property.

For example you could check if rates is an array as you expect.

0
votes

Axios' response returns a Promise, but your promise which is consoling the response does not. So you're basically setting your state to be {rates: undefined}. That is why you're getting that error in render. I think either you can do what Gegenwind has suggested or you can resolve a promise with the response instead of just consoling it.