I am trying to create an infinite scroll with my firestore document list using react-infinite-scroll-component. I set the limit to 5 for testing. The infinite scroll is working but it only shows the given limit of 5 list:
currently I created 25 different lists, and I limit firestore to show 5 at a time:
list 1
list 2
list 3
list 4
list 5
loading more...
after it loads it will load the same 5 list back and does not load a new list, and also loads in an infinite loop with the given 5 limit:
list 1
list 2
list 3
list 4
list 5
list 1
list 2
list 3
list 4
list 5
loading more...
here is my sample code below to get the query, I put it in a useEffect because it was in a context provider wrap in the the user page and the home page, both using infinite scroll:
import InfiniteScroll from 'react-infinite-scroll-component';
const [list, setList] = useState([]);
const [last, setLast] = useState(null);
useEffect(() => {
firestoreList
.orderBy('createdAt', "desc")
.limit(5)
.get()
.then((querySnapshot) => {
const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
setLast(lastVisible.data());
const postList = []
querySnapshot.forEach((doc) => {
postList.push(doc.data());
})
setList(postList);
})
.catch((err) => {
console.log(err)
})
},[]};
this is the code for the fetch data:
const {list, last, setList } = ListContext();
const fetchMoreData = () => {
firestoreList
.orderBy('createdAt', "desc")
.startAfter(last)
.limit(5)
.get()
.then(() => {
setList(list.concat(list));
})
.catch((err) => {
console.log(err)
})
};
and for the react-infinite-scroll-component:
<InfiniteScroll
dataLength={list.length}
next={fetchMoreData}
hasMore={true}
>
{list.map((a, i) => (
<div key={i}>
{a.allList}
<div>
))}
<InfiniteScroll>
How do I properly set the limit and make the other list appear and stop the loop?
I finally got it working now, I got the idea on this youtube channel, and I also should have defined a lastVisible in my fetchMoreData, and to stop the loop which gives an error of undefined.
const {list, last, setList, setLast } = ListContext();
const [notify, setNotify] = useState(null);
const fetchMoreData = () => {
const field = "createdAt";
firestoreList
.orderBy(field, "desc")
.startAfter(last[field]) //from Fireship channel, which loads the next data
.limit(5)
.get()
.then((querySnapshot) => {
const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
const postList = []
querySnapshot.forEach((doc) => {
postList.push(doc.data());
})
if (lastVisible !== undefined) {
setList([...list, ...postList]);
setLast(lastVisible.data());
} else {
setNotify("nothing to load.");
return;
}
})
.catch((err) => {
console.log(err)
})
};
It also works even without using 'react-infinite-scroll-component', just by using useEffect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With