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?