Skip to content

Instantly share code, notes, and snippets.

@lyjacky11
Last active November 17, 2022 23:29
Show Gist options
  • Save lyjacky11/c431f8e3648596af3dcac3f22741ffe1 to your computer and use it in GitHub Desktop.
Save lyjacky11/c431f8e3648596af3dcac3f22741ffe1 to your computer and use it in GitHub Desktop.
Pagination with Firebase & Firestore DB
import { db } from "../firebase";
import {
getDocs,
query,
collection,
orderBy,
startAfter,
limit,
} from "firebase/firestore";
const docLimit = 5;
export const fetchFirstBatchPosts = async function () {
try {
const data = await getDocs(
query(
collection(db, `posts`),
orderBy("timestamp", "desc"),
limit(docLimit)
)
);
let lastDoc;
let posts = [];
data.forEach((doc) => {
posts.push({
...doc.data(),
id: doc.id,
});
});
lastDoc = data.docs[data.docs.length - 1];
return { posts, lastDoc };
} catch (e) {
console.log(e);
}
};
export const fetchNextBatchPosts = async (doc) => {
try {
const data = await getDocs(
query(
collection(db, `posts`),
orderBy("timestamp", "desc"),
startAfter(doc),
limit(docLimit)
)
);
let posts = [];
let lastDoc;
data.forEach((doc) => {
posts.push({
...doc.data(),
id: doc.id,
});
});
lastDoc = data.docs[data.docs.length - 1];
return { posts, lastDoc };
} catch (e) {
console.log(e);
}
};
// USAGE:
useEffect(() => {
fetchFirstBatchPosts()
.then((res) => {
setPosts(res.posts);
setLastDoc(res.lastDoc);
})
.catch((err) => {
console.log(err);
});
}, []);
const fetchMorePosts = () => {
fetchNextBatchPosts(lastDoc)
.then((res) => {
setLastDoc(res.lastDoc);
setPosts(posts.concat(res.posts));
})
.catch((err) => {
console.log(err);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment