Skip to content Skip to sidebar Skip to footer

React Native Flat List (Infinite Scroll) Is Returning The Duplicate Records From Firebase

I was able to get Infinite Scroll working with React Native and Firebase, but there's an issue on retrieving the next 6 documents (limit is set to 6). It returns another 6 once the

Solution 1:

Flatlist may call your retrieval method twice. So be sure to use the loading prop to prevent the method from running.

onEndReached={(foo)=>{
  if (this.state.loading === false){
   this.makeAPizza(foo);
 }
}}

Solution 2:

The query gets the same results because it always starts at the same offset: startAt: 0.

To fix, keep a pageNumber in state, advanced as the user scrolls, then startAt: pageNumber*6

A few other comments about the code: State can be simplified...

this.state = {
  data: [],
  limit: 6,
  // startAt removed.  start at the end of data
  loading: false
};

Don't need retrieveMore. Its the same as retrieveUsers. retrieveUsers can be simplified...

// Retrieve Users
retrieveUsers = async () => {
  try {
    // Set State: Loading
    this.setState({ loading: true });

    // Firebase: Database + Settings
    const db = firebase.firestore();

    // Query
    console.log('Fetching Users')
    const query = await db.collection('users')
                          .where('company', '==', 'Google')
                          .orderBy('first_name')
                          .startAt(this.state.data.length)
                          .limit(this.state.limit);

    // Query Snapshot
    const querySnapshot = await query.get();

    // Document Data
    console.log('Document Data');
    const documentData = querySnapshot.docs.map(document => document.data());
    // console.log(documentData);


    // Set State
    this.setState({
      data: [...this.state.data, ...documentData],
      loading: false
    })
  }
  catch (error) {
    console.log(error);
  }
};

Notice that startAt is computed to be the length of data already retrieved. This works when data array is empty, also. Notice that logic to update state after the get is the same for the first or nth get: append new data to the existing data.

You don't need retrieveMore. Its the same as retrieveUsers. retrieveUsers can be simplified...

// ...
onEndReached={this.retrieveUsers}

Post a Comment for "React Native Flat List (Infinite Scroll) Is Returning The Duplicate Records From Firebase"