Ad

Two Axios Requests, One Response

- 1 answer

it appears the api im using breaks a list of 250 assets into multiple pages. im trying to call numerous pages to be listed in an ant design table

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

  componentDidMount() {
    axios.all([
      axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=true&price_change_percentage=24hr'),
      axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=2&sparkline=true&price_change_percentage=24hr')
    ])
    .then(axios.spread((res => {
      const data = res.data;
      this.setState({ data, loading: false })
  })))
}

  render() {

    const { data } = this.state;

    const tableData = data.map(row => ({
      Rank: row.market_cap_rank,
      Symbol: row.symbol,
      Name: row.name,
      Price: row.current_price,
      marketCap: row.market_cap,
      priceChange: row.price_change_percentage_24h,
      sparkline: row.sparkline_in_7d.price
    }))

    const columns = [{
      title: 'Rank',
      dataIndex: 'Rank',
      key: 'market_cap_rank',
    }, {
      title: 'Symbol',
      dataIndex: 'Symbol',
      key: 'symbol',
      render: (value) => {
        return <span>{value.toUpperCase()}</span>;
      },
    }, {
      title: 'Name',
      dataIndex: 'Name',
      key: 'name',
    }, {
      title: 'Price',
      dataIndex: 'Price',
      key: 'current_price',
      render: (value) => {
        return <span>$<b>{value.toFixed(2)}</b></span>;
      },
    }, {
      title: 'Market Cap',
      dataIndex: 'marketCap',
      key: 'market_cap',
      render: (value) => {
        return`$${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      },
...

    <Table 
      pagination="false"
      loading={this.state.loading} 
      dataSource={tableData} 
      columns={columns} 
      size="small"
    />

this works, but only displays the first page and not the second as well

sorry for the silly question, maybe someone can take a moment to assist me as this question probably stems from a lack of general understanding. it's sure nice to hear from other people on here! :)

Ad

Answer

You have to update your componentDidMount like below

axios.all([
      axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=true&price_change_percentage=24hr'),
      axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=2&sparkline=true&price_change_percentage=24hr')
    ])
    .then(resArr =>{
      const data = [];
      resArr.map(res=> data.push(...res.data));
      this.setState({ data, loading: false });
    });
Ad
source: stackoverflow.com
Ad