简体   繁体   English

React 和 Firebase Firestore V9 上一页分页返回“第一页”

[英]React and Firebase Firestore V9 Previous Page Pagination returning to "first page"

I'm at a loss here.我在这里不知所措。 I feel like I've been trying everything, and using the exact methods explained in other posts/tutorials everywhere.我觉得我一直在尝试一切,并使用其他帖子/教程中解释的确切方法。 I understand that you need to use a cursor and set the first and last visible document so that you can start after the last, in the case of moving forward, and start BEFORE the first, in the case of moving backwards.我知道您需要使用 cursor 并设置第一个和最后一个可见文档,以便在向前移动的情况下,您可以在最后一个之后开始,在向后移动的情况下,在第一个之前开始。

In my implementation, going forwards works fine.在我的实施中,前进工作正常。 However, when I utilize the previousPage function, it returns me to the first page, despite setting the 'first visible' document.但是,当我使用前一页 function 时,它会返回到第一页,尽管设置了“第一个可见”文档。 It returns to the first page even if I've already moved 3 'pages' forward.即使我已经向前移动了 3 个“页面”,它也会返回到第一页。

Clearly there is something I'm not understanding here..显然这里有些东西我不明白..

  const PAGE_SIZE = 6;
  const [posts, setPosts] = useState([]);
  const [lastVisible, setLastVisible] = useState(null);
  const [firstVisible, setFirstVisible] = useState(null);
  const [loading, setLoading] = useState(false);

  // Initial read to get first set of posts. 
  useEffect(() => {
    const q = query(
      collectionGroup(db, "bulletins"),
      orderBy("createdAt", "desc"),
      limit(PAGE_SIZE)
    );
    const unsubscribe = onSnapshot(q, (documents) => {
      const tempPosts = [];
      documents.forEach((document) => {
        tempPosts.push({
          id: document.id,
          ...document.data(),
        });
      });
      setPosts(tempPosts);
      setLastVisible(documents.docs[documents.docs.length - 1]);
      setFirstVisible(documents.docs[0]);
    });
    return () => unsubscribe();
  }, []);

  const nextPage = async () => {
    const postsRef = collectionGroup(db, "bulletins");
    const q = query(
      postsRef,
      orderBy("createdAt", "desc"),
      startAfter(lastVisible),
      limit(PAGE_SIZE)
    );
    const documents = await getDocs(q);
    updateState(documents);
  };

  const previousPage = async () => {
    const postsRef = collectionGroup(db, "bulletins");
    const q = query(
      postsRef,
      orderBy("createdAt", "desc"),
      endBefore(firstVisible),
      limit(PAGE_SIZE)
    );
    const documents = await getDocs(q);
    updateState(documents);
  };

  const updateState = (documents) => {
    if (!documents.empty) {
      const tempPosts = [];
      documents.forEach((document) => {
        tempPosts.push({
          id: document.id,
          ...document.data(),
        });
      });
      setPosts(tempPosts);
    }
    if (documents?.docs[0]) {
      setFirstVisible(documents.docs[0]);
    }
    if (documents?.docs[documents.docs.length - 1]) {
      setLastVisible(documents.docs[documents.docs.length - 1]);
    }
  };

You should use endAt() instead of endBefore() and also, you should pass the order reference which is the createdAt to the endAt() method.您应该使用endAt()而不是endBefore()并且,您应该将作为 createdAt 的订单参考传递给createdAt endAt()方法。 See code below:请参阅下面的代码:

  const PAGE_SIZE = 6;
  const [posts, setPosts] = useState([]);
  const [lastVisible, setLastVisible] = useState(null);
  const [firstVisible, setFirstVisible] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const q = query(
      collectionGroup(db, "bulletins"),
      orderBy("createdAt", "desc"),
      limit(PAGE_SIZE)
    );
    const unsubscribe = onSnapshot(q, (documents) => {
      const tempPosts = [];
      documents.forEach((document) => {
        tempPosts.push({
          id: document.id,
          ...document.data(),
        });
      });
      setPosts(tempPosts);
      setLastVisible(documents.docs[documents.docs.length - 1]);
      setFirstVisible(documents.docs[0]);
    });
    return () => unsubscribe();
  }, []);

  const nextPage = async () => {
    const postsRef = collectionGroup(db, "bulletins");
    const q = query(
      postsRef,
      orderBy("createdAt", "desc"),
      startAfter(lastVisible.data().createdAt), // Pass the reference
      limit(PAGE_SIZE)
    );
    const documents = await getDocs(q);
    updateState(documents);
  };

  const previousPage = async () => {
    const postsRef = collection(db, "bulletins");
    const q = query(
      postsRef,
      orderBy("createdAt", "desc"),
      endAt(firstVisible.data().createdAt), // Use `endAt()` method and pass the reference
      limitToLast(PAGE_SIZE)
    );
    const documents = await getDocs(q);
    updateState(documents);
  };

  const updateState = (documents) => {
    if (!documents.empty) {
      const tempPosts = [];
      documents.forEach((document) => {
        tempPosts.push({
          id: document.id,
          ...document.data(),
        });
      });
      setPosts(tempPosts);
    }
    if (documents?.docs[0]) {
      setFirstVisible(documents.docs[0]);
    }
    if (documents?.docs[documents.docs.length - 1]) {
      setLastVisible(documents.docs[documents.docs.length - 1]);
    }
  };

For more information, See Add a simple cursor to a query .有关详细信息,请参阅将简单的 cursor 添加到查询中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 React 将图像上传到 Firebase/Firestore v9 中的现有文档 - Upload Image to Existing doc in Firebase/Firestore v9 with React 无法到达 Cloud Firestore 后端 - React native Firebase v9 - Could not reach Cloud Firestore backend - React native Firebase v9 Firebase 从 Firestore v9 反应中获取数据 - Firebase get data from Firestore v9 react Firestore 集合到具有 Firebase v9 的对象数组 - Firestore collection to array of objects with Firebase v9 反应 JS 上的 Firebase v9 - Firebase v9 on react JS 实时数据库和 Firestore 的导入查询 Firebase web v9 - Import query for both Realtime Database and Firestore Firebase web v9 Firestore v9 预期 collection() 的第一个参数是 CollectionReference、DocumentReference 或 FirebaseFirestore - Firestore v9 Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore Firebase Firestore Query v9 工作“desc”但不是“asc”(索引两者) - Firebase Firestore Query v9 Works "desc" but not "asc" (indexed both) Firestore 使用 Firebase Client SDK V9 Modular with Admin 权限 - Firestore using Firebase Client SDK V9 Modular with Admin Privileges 如何在 firebase v9 中使用 useCollection react-firebase 钩子 - How to use useCollection react-firebase hook with firebase v9
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM