In the following code, I use the totalDoclNumbers and a docLimit to create a kind of pagination. If I assign totalDoclNumbers a static number, everything works.
But I want that totalDoclNumbers is actually the number of all documents in the collection and it should be calculated programatically. For this I tried the following:
import React, { useState, useEffect } from 'react';
import { db } from '../firebase';
import DeleteCard from './DeleteCard';
const List = () => {
const [cards, setCards] = useState([]);
const [beginAfter, setBeginAfter] = useState(0);
const [totalDoclNumbers, setTotalDoclNumbers] = useState(0);
useEffect(() => {
const fetchData = async () => {
const data = await db
.collection('FlashCards')
.orderBy('customId')
.limit(docLimit)
.startAfter(beginAfter)
.get();
setCards(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
setTotalDoclNumbers(docs.length - 1); // Causes ERROR
// setTotalDoclNumbers(100); // This works
};
fetchData();
}, [beginAfter]);
const docLimit = 10;
// Creating a menu for our documents (10 documents per each menu)
const RenderDocumentMenu = () =>
Array(totalDoclNumbers / docLimit)
.fill()
.map((_, i) => {
const onClick = () => setBeginAfter(docLimit * i);
return (
<div key={i} className='document__set' onClick={onClick}>
{docLimit * i + 1} to {docLimit * i + docLimit} Data
</div>
);
});
return (
<>
<div className='document'>
<RenderDocumentMenu />
</div>
<ul className='list'>
{cards.map((card) => (
<li key={card.id} className='list__item'>
<DeleteCard card={card} />
</li>
))}
</ul>
<AddCard />
</>
);
};
export default List;
But then I get this error: 'docs' is not defined no-undef
The line which causes the problem is this one: setTotalDoclNumbers(docs.length - 1);
What is wrong with my approach?
It is pretty clear that in your useEffect you need to access the docs
using data.docs
.
Like this
...
setTotalDoclNumbers(data.docs.length - 1);
...
Just a heads up - The data.docs
can be an empty array, so in that case, you are doing something like setTotalDoclNumbers(-1)
. So just watch out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.