Well. Assume that I have 100 documents in a firebase collection. I want to fetch 10 of them but also I need to get the total number at the same time to achieve my aim to create a pagination.
const updateDocuments = useCallback((documents, size) => {
dispatch({
type: actions.UPDATE_DOCUMENTS,
payload: {documents, size}
});
}, []);
useEffect(() => {
const ref = db.collection('documents').orderBy('createdAt', 'desc');
const unsubscribe = ref.onSnapshot(async snapshot => {
const documents = await fetchDocuments(snapshot)
const length = await fetchDocumentsCount(snapshot)
updateDocuments(documents, length);
});
return () => {
unsubscribe();
}
}, [updateDocuments]);
Ok now it is for sure that the snapshot above will fetch 100 documents and will give me total count as 100 as well. Experts already can guess that I use context api and I will push 100 documents and total number to this object below and I want to use it in whatever component I like.
const state = {
documents: [],
size: 0
}
So if I created ref as
const ref = db.collection('documents').orderBy('createdAt', 'desc').limit(10);
Then I would get 10 documents but also the total number of documents become 10.
So how can I get 10 documents but the total number of documents (in this example 100) within same useEffect?
Note:
export const fetchDocuments = data => {
const documents= data.docs.map(doc => {
const { name, email} = doc.data();
return {
name,
email,
}
})
return documents;
}
export const fetchDocumentsCount = data => data.size;