Xehanorth
Xehanorth

Reputation: 99

React Native How to get multiple APIs at the same time?

For my project, I have to get several APIs in my projects, these APIs are linked to the others, i.e. they have the same data ...

Here is my code


export default class App extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    Promise.all([
      getData(),
      getData('?page=2'),
    ])
      .then(([dataSource1, dataSource2]) => {
        this.setState({
          isLoading: false,
          isLoading2: false,
          dataSource1,
          dataSource2,
        });
      })
      .catch((error) => {
        // handle errors
      });
  }

  render() {
    const getData = (subpath = '') => fetch(`https://api.rawg.io/api/games${subpath}`)
      .then(res => res.json())
      .then(result => result.results);
    console.log(getData)
        

  }

I tried with axios but without success ...

When I remove the comment, it shows me only the second fetch ...

Upvotes: 1

Views: 1280

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

You need two separate fetch calls for each API. To wait for both to finish, use Promise.all.

const getData = (subpath = '') => fetch(`https://api.rawg.io/api/games${subpath}`)
    .then(res => res.json())
    .then(result => result.results);
componentDidMount() {
    Promise.all([
        getData(),
        getData('?page=2'),
    ])
        .then(([dataSource1, dataSource2]) => {
            this.setState({
                isLoading: false,
                isLoading2: false,
                dataSource1,
                dataSource2,
            });
        })
        .catch((error) => {
            // handle errors
        });
}

Upvotes: 1

Related Questions