We have a flatlist of "thoughts", and are getting the first 10 items, followed by the next 7 every page after.
However, when you reach the end of the first "page", the same data gets appended to the array, and you scroll through the same page over and over
Our flatlist:
<FlatList
ref={scrollRef}
data={thoughts}
renderItem={renderItem}
keyExtractor={item => item.key}
contentContainerStyle={{ marginTop: 45, paddingBottom: 50 }}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
onRefresh={refresh}
refreshing={isLoading}
onEndReached={getMore} // <------- Get the next page of posts
/>
Our "getMore" - we first convert the date_created from an object to a firebase timestamp, because we are sorting by date when we call firebase.
const getMore = async() => {
const lastItemIndex = thoughts.length - 1;
const seconds = thoughts[lastItemIndex].date_created._seconds;
const nanoseconds = thoughts[lastItemIndex].date_created._nanoseconds;
const lastTime = new firebase.firestore.Timestamp(seconds, nanoseconds); //-- the firebase timestamp
const getMoreThoughtsOneCategory = firebase.functions().httpsCallable('getMoreThoughtsOneCategory');
getMoreThoughtsOneCategory({
index: lastItemIndex,
category: selectedCategory,
date_created: lastTime.toDate(),
}).then((result) => {
setThoughts(thoughts.concat(result.data)); //Append the collection
}).catch((err) => {
console.log(err);
});
};
Our getMoreThoughtsOneCategory firebase cloud function:
exports.getMoreThoughtsOneCategory = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
admin.firestore()
.collection('thoughts')
.where("category", "==", data.category)
.orderBy('date_created', 'desc')
.startAfter(data.date_created)
.limit(7)
.get()
.then((query) => {
const thoughts = [];
query.forEach((res) => {
const {
...Get fields
} = res.data();
thoughts.push({
...Set fields
});
});
resolve(thoughts);
return null;
}).catch(err => {
console.log("Errors from getting more thoughts " + err);
reject(err);
})
});
})
And here is the initial query for the first "page" of thoughts, the data that keeps repeating:
exports.getThoughtsOneCategory = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
admin
.firestore()
.collection('thoughts')
.where("category", "==", data.category)
.orderBy('date_created', 'desc')
.limit(9)
.get()
.then((query) => {
const thoughts = [];
query.forEach((res) => {
const {
... Get fields
} = res.data();
thoughts.push({
... Set fields
});
index++;
});
resolve(thoughts);
return null;
}).catch(err => {
console.log("Error from getting first set of thoughts " + err);
reject(err);
})
});
});
To summarize, we get the first 9 items. When we reach the end of the flatlist, we should get the next 7 items in the db, but we just get the first 7 items appended to the array. How can we fix this issue?