From d82495c265ccb67435c11b167bb477c02481ec01 Mon Sep 17 00:00:00 2001 From: nefelitav Date: Mon, 18 Mar 2024 10:12:46 +0100 Subject: [PATCH] fix pagination issue --- src/components/Chat.tsx | 4 +- src/components/UsersList.tsx | 99 +++++++++++++++++++++++++++++++++--- src/types/types.tsx | 1 + 3 files changed, 94 insertions(+), 10 deletions(-) diff --git a/src/components/Chat.tsx b/src/components/Chat.tsx index 086814d..d26a061 100644 --- a/src/components/Chat.tsx +++ b/src/components/Chat.tsx @@ -24,9 +24,7 @@ const Chat: React.FC = ({ socket }) => { // Effect to listen for incoming messages from the socket useEffect(() => { setMessages([]); - console.log("selected user"); socket.onmessage = (event) => { - console.log("listening"); const newMessage = JSON.parse(event.data); // const userString = localStorage.getItem("user"); // if (userString) { @@ -53,7 +51,7 @@ const Chat: React.FC = ({ socket }) => { return (
- +
{!showProfile && ( diff --git a/src/components/UsersList.tsx b/src/components/UsersList.tsx index cba7381..720a606 100644 --- a/src/components/UsersList.tsx +++ b/src/components/UsersList.tsx @@ -2,21 +2,71 @@ import React, { useState, useEffect } from 'react'; import { UsersListProps, UserData, UserWithChatData } from "../types"; import "../index.css"; -const UsersList: React.FC = ({ setShowProfile, setSelectedUser, handleShowUser, setChatId }) => { +const UsersList: React.FC = ({ setShowProfile, setSelectedUser, handleShowUser, setChatId, socket }) => { // State variables const [users, setUsers] = useState([]); const [currentPage, setCurrentPage] = useState(0); - const [totalPages] = useState(3); + const [numberOfUsers, setNumberOfUsers] = useState(0); + const [addedUsers, setAddedUsers] = useState(0); + const [newUsers, setNewUsers] = useState(0); + const [totalPages, setTotalPages] = useState(0); + const [nextPage, setNextPage] = useState(false); + const pageSize : number = 3; + console.log(socket); const [isLoading, setIsLoading] = useState(false); // State to track loading state // Get user from local storage const userString = localStorage.getItem("user"); const user: UserData | null = userString ? JSON.parse(userString) : null; + // const [onlineUsers, setOnlineUsers] = useState([]); + // useEffect(() => { + // console.log("!!!"); + // // Function to fetch online users + // const fetchOnlineUsers = async () => { + // console.log("!!"); + // try { + // // Send a message to the WebSocket server indicating you want to fetch online users + // if (socket.readyState === WebSocket.OPEN) { + // // Send a message to the WebSocket server indicating you want to fetch online users + // const msg = { + // "action" : "getOnlineUsers", + // "sender_id": String(user?.id) + // }; + // socket.send(JSON.stringify(msg)); + // } else { + // console.log("WebSocket connection is still in CONNECTING state."); + // } + // } catch (err) { + // console.log(err); + // } + // }; + // console.log("!!!!!"); + // fetchOnlineUsers(); + // // Set up an interval to fetch online users every 5 minutes (300000 milliseconds) + // const interval = setInterval(() => { + // fetchOnlineUsers(); + // }, 9999999999999999999999999999999999999999999999999999); + + // // Handle messages received from WebSocket server + // socket.onmessage = (event) => { + // console.log("-----", event.data); + // const data = JSON.parse(event.data); + // if (data.action === 'updateOnlineUsers') { + // // Update online users state with data received from WebSocket server + // setOnlineUsers(data.online_user_ids); + // } + // }; + // console.log(onlineUsers); + + // // Clean up function to clear interval on component unmount + // return () => clearInterval(interval); + // }, []); // Empty dependency array ensures useEffect runs only once after initial render + useEffect(() => { const fetchUsers = async () => { try { setIsLoading(true); // Set loading state to true - const response = await fetch(`http://localhost:8081/user/all?pageNo=${currentPage}&pageSize=${totalPages}`, { + const response = await fetch(`http://localhost:8081/user/all?pageNo=${currentPage}&pageSize=${pageSize}`, { method: "GET", credentials: "include", headers: { @@ -34,19 +84,26 @@ const UsersList: React.FC = ({ setShowProfile, setSelectedUser, // Parse the response body as JSON const responseBody = await response.json(); + setTotalPages(responseBody.totalPages); + const redisData = responseBody.redisData; + // Update users state with new data // Do not add duplicates - for (const key in responseBody) { + setAddedUsers(0); + let counter = 0; + for (const key in redisData) { const tokens = key.split("chat:"); - const parsedResponse = JSON.parse(responseBody[key]); + const parsedResponse = JSON.parse(redisData[key]); setUsers(users => { const userSet = new Set(users.map(user => user.user.id)); if (String(user?.id) === parsedResponse.user2.id) { if (!userSet.has(parsedResponse.user1.id)) { + counter++; return [...users, { user: parsedResponse.user1, chat_id: tokens[1] }]; } } else if (String(user?.id) === parsedResponse.user1.id) { if (!userSet.has(parsedResponse.user2.id)) { + counter++; return [...users, { user: parsedResponse.user2, chat_id: tokens[1] }]; } } @@ -54,8 +111,16 @@ const UsersList: React.FC = ({ setShowProfile, setSelectedUser, return users; }); } + setNumberOfUsers(prevNumberOfUsers => prevNumberOfUsers + counter); + setAddedUsers(prevAddedUsers => prevAddedUsers + counter); setIsLoading(false); // Set loading state to false + // if (addedUsers === 0) { + // if ((numberOfUsers % pageSize === 0) && currentPage > 0) { + // console.log("decrementing - current page: ", currentPage, " number of users: ", numberOfUsers); + // setCurrentPage(currentPage - 1); + // } + // } } catch (error) { console.error('Error fetching users:', error); @@ -63,7 +128,7 @@ const UsersList: React.FC = ({ setShowProfile, setSelectedUser, } }; fetchUsers(); - }, [currentPage, totalPages, user?.id]); // the dependencies + }, [currentPage, user?.id, newUsers]); // the dependencies return ( @@ -96,7 +161,27 @@ const UsersList: React.FC = ({ setShowProfile, setSelectedUser,
{!isLoading && (
-
diff --git a/src/types/types.tsx b/src/types/types.tsx index e13154c..12b4dd9 100644 --- a/src/types/types.tsx +++ b/src/types/types.tsx @@ -34,6 +34,7 @@ export interface UsersListProps { setSelectedUser: React.Dispatch>; handleShowUser: (user: UserData | null) => void; setChatId: React.Dispatch>; + socket: WebSocket; } export interface UserData {