'onEndReached running in FlatList when page loads in react-native-web

I have been experimenting with infinite scrolling in React Native. The aim is to load 400 items overall and to load 20 each time the user hits the bottom of the FlatList element. In react-native-web, what's going on is that onEndReached keeps on running until all 400 elements have loaded. I have set onEndReachedThreshold to 0.1 (I assume that means that is to trigger fetching more data when the user is less than 10% away from the bottom of the list). I am not sure how to get it to load just 20 elements and to load the remaining elements when the user interacts with the FlatList. I've shared my code below.

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, ActivityIndicator } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default function App() {

  const [pageResults, setPageResults] = React.useState([])
  const [page, setPage] = React.useState(1)
  const [loading, setLoading] = React.useState(false)
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    setLoading(true) 
    fetch(`https://randomuser.me/api/?page=${page}&results=20`).then(res => res.json()).then(res => {
        const results = res.results

        setPageResults([...pageResults, ...results])
        setCount(count + 20) 
        setLoading(false)

        console.log(page)
    })

  }, [page])
 

  const renderItem = ({ item }) => {
    return (
      <View key={item.name} style={styles.listItem}>
        <Text>{item.name.first}</Text>
      </View>
    )

  } 


  return (
    <View style={styles.container}>
      <FlatList
        data={pageResults}
        style={styles.list}
        renderItem={renderItem} 
        onEndReachedThreshold={0.1}
        onEndReached={({ distanceFromEnd }) => {
          if (count < 400 && !loading) {
              setPage(page + 1)
          } 
          }} 
        ListFooterComponent={loading && <ActivityIndicator />} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  list: {
    width: "100%",
    height: "100%"
  },
  listItem: {
    width: "100%",
    height: "40px",
    padding: "8px",
    alignItems: "flexStart",
  },
});


Solution 1:[1]

I have a similar problem, my flatlist launch the function at onEndReached, always at the start of the app, even if i put the lowest onEndReachedThreshold it keeps launching at the start. In my case it was something of design, I add some margin at the bottom and it works right.

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 PabloTz