Leminur
Leminur

Reputation: 361

How to create a flatlist with infinite scroll with local data? (Possible useState misuse)

I have a problem trying to create a FlatList with infinite scroll using local data. I want the list to load 20 different elements every time it reaches the bottom. Here is the list:

                <FlatList
                  contentContainerStyle={styles.airportLatestSearchlist}
                  data={filteredAirportList}
                  renderItem={renderAirportItem}
                  keyExtractor={(item) =>
                    filteredAirportList.indexOf(item).toString()
                  }
                  onEndReached={increaseTotalFilteredResults}
                  onEndReachedThreshold={0.1}
                />

The data filteredAirportList is loaded once the user starts typing in the search box. This is the function that filters the data which is already stored.

  const filterAirportSearch = (value) => {
    const managedValue = value.toLowerCase();
    const filteringAirports = airportList.filter(
      (airport) =>
        airport.airport_name?.toLowerCase().includes(managedValue) ||
        airport.city?.toLowerCase().includes(managedValue) ||
        airport.country?.toLowerCase().includes(managedValue) ||
        airport.icao?.toLowerCase().includes(managedValue) ||
        airport.iata?.toLowerCase().includes(managedValue),
    );
    var numberListHelper = filteringAirports;
    numberListHelper.length = numberElementsList;
    setTotalFilteredAirportList(filteringAirports);
    setFilteredAirportList(numberListHelper);
  };

And this is the function that is called once the user scrolls to the bottom:

  const increaseTotalFilteredResults = () => {
    let numberHelper = numberElementsList;
    if (numberHelper < totalFilteredAirportList.length) {
      numberHelper = numberElementsList + 20;
    }
    setNumberElementsList(numberHelper);

    if (Object.keys(totalFilteredAirportList).length > 0) {
      let filteredListUpdate = totalFilteredAirportList;
      filteredListUpdate.length = numberHelper;
      setFilteredAirportList(filteredListUpdate);
    }
  };

However, every time that this function is called:

numberListHelper.length = numberElementsList;

It changes the length for the filteringAirports state as well and I can't load the rest of the data. Is it actually a bug or am I changing directly by a reference?

Here is a visual part of the problem.

Before .length is called Before .length is called

After .length is called After .length is called

Thanks!

Upvotes: 0

Views: 309

Answers (1)

ludwiguer
ludwiguer

Reputation: 2245

Yes, if you do newArr = oldArr you are just copying the reference, so any change you make to any of them will be reflected in both, if you want to clone an array do this instead

let numberListHelper = [...filteringAirports]

Upvotes: 2

Related Questions