'Fetch data from multiple pages of an API in react native

I'm trying to get information from a video game API and put it in my list. However, the API is divided in multiple pages (which I don't know how many there are).

I tried this solution: How to fetch data over multiple pages?

Then I tried another solution (code snippet below updated), but it's giving me an error:

Maximum Update Depth Exceeded...

Probably because it never stops updating my 'currentPage' variable

After hours of debugging I gave up.

Here is my file:

import { Card, CardItem } from "native-base";

export default class App extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: [],
      currentPage: 1
    };
  }
 
  getUserFromApi = () => {

      return fetch('https://api.rawg.io/api/games?page=' + this.state.currentPage +'&platforms=18', {
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "rawg-video-games-database.p.rapidapi.com",
          "x-rapidapi-key": "495a18eab9msh50938d62f12fc40p1a3b83jsnac8ffeb4469f"
        }
      })
        .then(response => response.json())
        .then(responseJson => {
          this.setState({
            isLoading: false,
            dataSource: this.state.dataSource.concat(responseJson.results)
          });
        })
        .catch(error => console.log(error));
    
    
  };

    componentDidMount() {
      this.getUserFromApi();

    }
  

    render() {

      const { isLoaded, items } = this.state;
      
    
        if (this.state.isLoading) {
          return (
            <View style={styles.progress}>
              <ActivityIndicator size="large" color="#01CBC6" />
            </View>
          );
        }

        return (
          <FlatList
            data={this.state.dataSource}
            onEndReached={ this.setState({ currentPage: this.state.currentPage + 1 }) } 


Solution 1:[1]

Solution 1

Iterate over the API incrementing the currentPage value until no results are returned (therefore, indicating the end of the list).

function fetchAllGamesFromAPI() {
    let endOfList = false;
    let items = [];
    let currentPage = 1;

    while(endOfList === false) {
        const result = fetchGamesFromAPI(currentPage);

        endOfList = !result.length;
        items = [...items, ...result];
        currentPage += 1;
    }
    
    return items;
}

Of course, this could take incredibly long due to the fact that you (don't know how many there are). Which leads to

Solution 2

Fetch additional data as the user scrolls to the (or near the) end of the list via an API provided by FlatList. https://reactnative.dev/docs/flatlist#onendreached


const onEndReached = () => {
    this.setState({
        currentPage = currentPage + 1;
    })
    
    fetchGamesFromAPI(currentPage);
};

<FlatList
    ...
    onEndReached={ onEndReached } />

Solution 2:[2]

If you have django as backend framework you can use.

React.useEffect(() => {
    const getAllGames = async(page: number|null): void => {
      if (Number.isInteger(page)){
        const result = await fetch(apiURL + "/games?page="+page)
        const data = await result.json()
        const { results: games } = data;
        if (data.next) { 
          setTimeout(
            getAllGames(
              parseInt(data.next.charAt(data.next.length-1))), 10000)
        }
        setGames(previousGames => [...games, ...previousGames]);
      }
    }
    getAllGames(1)
  }, []);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nick Kim
Solution 2