Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added message loading system #62

Merged
merged 1 commit into from
Sep 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 57 additions & 30 deletions client/src/components/Negotiate/Chat.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import styles from './chat.module.css';
import io from 'socket.io-client'
import { useState, useRef, useEffect, useContext } from 'react';
import { addDoc, collection, doc, getDoc } from 'firebase/firestore';
import { addDoc, collection, doc, getDoc, orderBy, query, getDocs } from 'firebase/firestore';
import { db } from '../../../firebase';
import { AuthContext } from '../context/Authcontext';
import { useNavigate } from 'react-router-dom';
Expand All @@ -19,13 +19,15 @@

const { currentUser } = useContext(AuthContext);
const [socket, setSocket] = useState(null);
const [currentRoomID, setRoomID] = useState(1);
const [currentRoomID, setRoomID] = useState(null);
const [prevRoomID, setPrevRoomID] = useState(null);
const [userType, setUserType] = useState('buyers');
const [contacts, setContacts] = useState(null);
const [message,setmessage]=useState();
const[messages, setMessages] = useState();
const navigate = useNavigate();
const [currperson,setperson]=useState();
const [loading, setLoading] = useState(true);

useEffect(()=>{
if(!currentUser){
Expand All @@ -37,6 +39,7 @@

loadContacts(currentUser.uid, userType).then((result)=>{
setContacts(result);
setLoading(false);
})

console.log("current user id ", currentUser.uid);
Expand All @@ -45,11 +48,11 @@
console.log("disconnected");
newSocket.disconnect();
};
},[currentUser])

Check warning on line 51 in client/src/components/Negotiate/Chat.jsx

View workflow job for this annotation

GitHub Actions / Lint Client Code

React Hook useEffect has a missing dependency: 'userType'. Either include it or remove the dependency array

useEffect(()=>{
if(contacts!=null){
console.log("contacts ", contacts);
// console.log("contacts ", contacts);
}
},[contacts])

Expand Down Expand Up @@ -82,14 +85,17 @@
}, [socket])

useEffect(()=>{

//switch rooms/contacts
if(socket){
switchRooms(socket, prevRoomID, currentRoomID);
loadMessage(currentRoomID);
}
if(socket){
switchRooms(socket, prevRoomID, currentRoomID);
loadMessage(currentRoomID).then((result)=>{setMessages(result)});
}
}, [currentRoomID])

Check warning on line 93 in client/src/components/Negotiate/Chat.jsx

View workflow job for this annotation

GitHub Actions / Lint Client Code

React Hook useEffect has missing dependencies: 'prevRoomID' and 'socket'. Either include them or remove the dependency array

useEffect(()=>{
console.log(messages);
}, [messages])


const handleClick = async ()=>{
//broadcast message
Expand All @@ -101,6 +107,15 @@
const handleChange = (event) => {
setmessage(event.target.value);
};

if (loading) {
return <div><h1>Loading contacts...</h1></div>; // Show a loading message or spinner
}

if (!contacts || Object.keys(contacts).length === 0) {
return <div>No contacts available</div>; // Handle case where no contacts are available
}

return (
<div className={styles.chitchat}>
<div className={styles.chatui}>
Expand Down Expand Up @@ -136,7 +151,9 @@
<button
key={key}
onClick={() => {
loadMessage(contact.roomID)
// loadMessage(contact.roomID)
setPrevRoomID(currentRoomID);
setRoomID(contact.roomID);
setperson(`${contact.farmer_name}`)}}
style={{ marginBottom: '10px', cursor: 'pointer',textAlign:'center' }}
className={styles.cnt1}
Expand Down Expand Up @@ -179,17 +196,6 @@
</div>
</div>
</div>
{/*
<button onClick={()=>{
if(currentRoomID<3){
setPrevRoomID(currentRoomID);
setRoomID(currentRoomID+1);
}
else{
setPrevRoomID(currentRoomID);
setRoomID(1);
}
}}>Switch Room</button> */}
</div>
);
}
Expand All @@ -200,15 +206,19 @@
}

const uploadMessage = async (currentRoomID,mess,userId)=>{
try {
await addDoc(collection(db, 'chats', `${currentRoomID}`, 'messages'), {
message: `${mess}`,
timeStamp: new Date(),
// user: currentUser.uid,
user:`${userId}`
}).then(console.log("message sent"));
} catch (error) {
console.error("Error uploading message:", error);
if(currentRoomID){
try {
await addDoc(collection(db, 'chats', `${currentRoomID}`, 'messages'), {
message: `${mess}`,
timeStamp: new Date(),
// user: currentUser.uid,
user:`${userId}`
}).then(console.log("message sent"));
} catch (error) {
console.error("Error uploading message:", error);
}
}else{
console.log("select room");
}
}

Expand All @@ -230,6 +240,23 @@
}

const loadMessage = async (currentRoomID)=>{
//TODO
console.log(`fetching messages from ${currentRoomID}`);
try {
const messagesCollectionRef = collection(db, "chats", `${currentRoomID}`, "messages");
const q = query(messagesCollectionRef, orderBy('timeStamp', 'asc'));

const querySnapshot = await getDocs(q);
const fetchedMessages = querySnapshot.docs.map(doc=>{
const data = doc.data();
return{
user:data.user,
text:data.message
}
})
// console.log(fetchedMessages);
return fetchedMessages;
} catch (error) {
console.error("Error fetching messages: ", error);
}

}
Loading