Hello I have made a simple AXIOS get request and receive an array of objects. But the example I used to achieve this returns all array at one and I need to separate the objects so I could use each of them separately.

class apitest extends Component {
  constructor(props) {
    super(props);

    this.state = {
      cryptos: []
    };
  }

  componentDidMount() {
    axios
      .get(
        "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,XRP,BCH,EOS,TRX&tsyms=EUR,CHANGE&api_key=xxx"
      )
      .then(res => {
        const cryptos = res.data;
        console.log(cryptos);
        this.setState({ cryptos: cryptos});
      });
  }

  render() {
    return (
      <div className="test">
        {Object.keys(this.state.cryptos).map(key => (
          <div id="crypto-container">
            <span className="left">{key}</span>
            <span className="right">
              <NumberFormat
                value={this.state.cryptos[key].EUR}
                displayType={"text"}
                decimalPrecision={2}
                thousandSeparator={true}
                prefix={"€"}
              />
            </span>
          </div>
        ))}
      </div>
    );
  }
}

export default apitest;

2 Answers

2
Marcus On Best Solutions

What you are receiving is an object whose properties are themselves objects. To iterate over those properties, you ca use Object.keys(), as in:


Object.keys(response).forEach((property) => {
    // Access each object here by using response[property]...
})

You may also need to convert the response from JSON first, but I'm sure you know how to do that.

-1
Lluís Marfany On

The response from AXIOS is an JSON array? If yes, did you try to force the json response in AXIOS?

axios
  .get(
    "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,XRP,BCH,EOS,TRX&tsyms=EUR,CHANGE&api_key=xxx",
    {
      responseType: 'json',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    }
  )
  .then(...)

Apart of this, the way you iterate in render it would be better:

  • Check if this.state.cryptos exists before iterate it.
  • Put the key on the first-indented div on the iterator; ReactJs need it.
  • Create an object iterator instead of a key iterator.

Render refactoring:

render() {
  if(this.state.cryptos.length === 0) return null;

  return (
    <div className="test">
      {this.state.cryptos.map((crypto, key) => (
        <div id="crypto-container" key={key}>
          <span className="left">{key}</span>
          <span className="right">
            <NumberFormat
              value={crypto.EUR}
              displayType={"text"}
              decimalPrecision={2}
              thousandSeparator={true}
              prefix={"€"}
            />
          </span>
        </div>
      ))}
    </div>
  );
}