From fc8eb79b98bbea558bd614dc71dd66b72ab9b0c0 Mon Sep 17 00:00:00 2001
From: MohamedBassem <me@mbassem.com>
Date: Sun, 17 Mar 2024 13:12:11 +0000
Subject: feature: Implemente pagination support

---
 .../dashboard/bookmarks/BookmarksGrid.tsx          | 47 ++++++++++++++++------
 1 file changed, 35 insertions(+), 12 deletions(-)

(limited to 'apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx')

diff --git a/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx b/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx
index 644991bb..b689a192 100644
--- a/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx
+++ b/apps/web/components/dashboard/bookmarks/BookmarksGrid.tsx
@@ -1,6 +1,7 @@
 "use client";
 
 import { useMemo } from "react";
+import { ActionButton } from "@/components/ui/action-button";
 import { api } from "@/lib/trpc";
 import tailwindConfig from "@/tailwind.config";
 import { Slot } from "@radix-ui/react-slot";
@@ -10,6 +11,7 @@ import resolveConfig from "tailwindcss/resolveConfig";
 import type {
   ZBookmark,
   ZGetBookmarksRequest,
+  ZGetBookmarksResponse,
 } from "@hoarder/trpc/types/bookmarks";
 
 import EditorCard from "./EditorCard";
@@ -55,24 +57,45 @@ export default function BookmarksGrid({
   showEditorCard = false,
 }: {
   query: ZGetBookmarksRequest;
-  bookmarks: ZBookmark[];
+  bookmarks: ZGetBookmarksResponse;
   showEditorCard?: boolean;
+  itemsPerPage?: number;
 }) {
-  const { data } = api.bookmarks.getBookmarks.useQuery(query, {
-    initialData: { bookmarks: initialBookmarks },
-  });
+  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
+    api.bookmarks.getBookmarks.useInfiniteQuery(query, {
+      initialData: () => ({
+        pages: [initialBookmarks],
+        pageParams: [query.cursor],
+      }),
+      initialCursor: null,
+      getNextPageParam: (lastPage) => lastPage.nextCursor,
+    });
+
   const breakpointConfig = useMemo(() => getBreakpointConfig(), []);
-  if (data.bookmarks.length == 0) {
+  const bookmarks = data!.pages.flatMap((b) => b.bookmarks);
+  if (bookmarks.length == 0) {
     return <p>No bookmarks</p>;
   }
   return (
-    <Masonry className="flex gap-4" breakpointCols={breakpointConfig}>
-      {showEditorCard && (
-        <BookmarkCard>
-          <EditorCard />
-        </BookmarkCard>
+    <>
+      <Masonry className="flex gap-4" breakpointCols={breakpointConfig}>
+        {showEditorCard && (
+          <BookmarkCard>
+            <EditorCard />
+          </BookmarkCard>
+        )}
+        {bookmarks.map((b) => renderBookmark(b))}
+      </Masonry>
+      {hasNextPage && (
+        <ActionButton
+          loading={isFetchingNextPage}
+          onClick={() => fetchNextPage()}
+          className="mx-auto w-min"
+          variant="ghost"
+        >
+          Load More
+        </ActionButton>
       )}
-      {data.bookmarks.map((b) => renderBookmark(b))}
-    </Masonry>
+    </>
   );
 }
-- 
cgit v1.2.3-70-g09d2

