I am creating an application that connects volunteers to newcomers using ReactJS. In the app I have developed a chat mechanism that will help newcomers connect with volunteers and vice-versa. I have implemented a feature that displays the featured volunteers with their info and a button that says 'contact'. I have hooked up the contact button so that when pressed the user gets directed to the chat and a new conversation list document is created in MongoDB using the POST request.
The problem I am running into is that the POST request keeps on running every time I click the 'contact' button resulting in multiple duplicates of the username getting rendered. I am struggling with finding a solution to the problem. I would like only one username to get rendered to the page and not have a whole bunch of duplicates. Any help is greatly appreciated.
The GET method that grabs the email and POST method that creates a new document
**VolunterCard.jsx**
React.useEffect(() => {
const getImage = async () => {
let response = await fetch(`/image/cass@gmail.com`);
let data = await response.json();
console.log(`Data is:`, data);
setVolunteer(data);
};
getImage();
}, []);
const createConversation = async () => {
const newConversation = {
members: {
senderEmail: user.email,
recieverEmail: volunteer.email
},
};
const data = JSON.stringify(newConversation)
await fetch("/conversation", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: data,
})
};```
**Conversation.jsx (Where the user gets rendered)**
useEffect(() => {
const chatMembers = conversation.members.find(
(member) => member !== currentUser.email
);
const getUsersFirstName = async () => {
try {
const response = await axios.get("/name?email=" + chatMembers);
setUser(response.data);
} catch (err) {
console.log(err.message);
}
};
getUsersFirstName();
}, [currentUser, conversation, isLoading]);
if (isLoading) {
return <div>isLoading...</div>;
}
return (
<div style={{cursor: 'pointer'}}>
{user.firstName} {user.lastName} - {user.email}
</div>
);
};```
**converstionModel.js**
```const mongoose = require("mongoose")
const conversationSchema = new mongoose.Schema({
members: {
type: Array,
}
}, { timestamps: true});
const conversationModel = mongoose.model("Members", conversationSchema);
const createMembers = async (members) => {
const newMembers = await conversationModel.create(members);
return newMembers
};```