From 0fed60dc83db376ddb3f7c835894db29dfe51994 Mon Sep 17 00:00:00 2001
From: Andrew Lee <alee14498@protonmail.com>
Date: Mon, 5 Feb 2024 17:50:51 -0500
Subject: Pagination; Disabled form when sending

---
 src/components/Guestbook.jsx | 39 +++++++++++++++++++++++++++++++--------
 1 file changed, 31 insertions(+), 8 deletions(-)

(limited to 'src/components/Guestbook.jsx')

diff --git a/src/components/Guestbook.jsx b/src/components/Guestbook.jsx
index a959b5a..5935d04 100644
--- a/src/components/Guestbook.jsx
+++ b/src/components/Guestbook.jsx
@@ -7,31 +7,52 @@ import GuestbookForm from "./GuestbookForm.jsx";
 class Guestbook extends Component {
     state = {
         message: null,
-        error: null
+        error: null,
+        page: 1,
     };
 
-    fetchMessages = async () => {
+    fetchMessages = async (page) => {
+        const perPage = 10;
+
         try {
-            const message = await pb.collection('guestbook').getFullList({
+            const result = await pb.collection('guestbook').getList(page, perPage, {
                 sort: '-created',
             });
-            this.setState({ message });
+            this.setState({
+                message: result.items,
+                totalPages: result.totalPages
+            });
         } catch (error) {
             this.setState({ error: `Failed to fetch data: ${error.message}` });
             console.error('Failed to fetch data:', error);
         }
     }
 
+    refresh = async () => {
+        await this.fetchMessages(this.state.page);
+    }
+
     async componentDidMount() {
-        await this.fetchMessages();
+        await this.fetchMessages(this.state.page);
     }
 
-    refresh = async () => {
-        await this.fetchMessages();
+    handleNext = async () => {
+        const nextPage = this.state.page + 1;
+        if (nextPage > this.state.totalPages) {
+            return;
+        }
+        this.setState({ page: nextPage });
+        await this.fetchMessages(nextPage);
+    }
+
+    handlePrevious = async () => {
+        const previousPage = this.state.page - 1;
+        this.setState({ page: previousPage });
+        await this.fetchMessages(previousPage);
     }
 
     render() {
-        const { message, error } = this.state;
+        const { message, error, page, totalPages } = this.state;
 
         return (
             <div>
@@ -52,6 +73,8 @@ class Guestbook extends Component {
                         ))}
                     </div>
                 )}
+                {page > 1 && <button class="margin" onClick={this.handlePrevious}>Previous</button>}
+                {page < totalPages && <button class="margin" onClick={this.handleNext}>Next</button>}
             </div>
         );
     }
-- 
cgit v1.2.3

