generated from agiledev-students-fall2023/generic-project-repository
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #134 from agiledev-students-fall2023/fetch-friends…
…-expense-page Update functionality for add friends
- Loading branch information
Showing
6 changed files
with
111 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,37 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
const { User } = require("../models/User.js"); | ||
|
||
// Hardcoded user data to simulate a database | ||
let userData = { | ||
"name": "Sallyanne", | ||
"email": "[email protected]", | ||
"phone": "764-995-4333", | ||
"avatar": "https://robohash.org/eligendiquiased.png?size=50x50&set=set1", | ||
} | ||
router.post('/', async (req, res) => { | ||
const { currentUserId, friendUserId } = req.body; | ||
|
||
// Endpoint to get user data after search | ||
router.get('/', (req, res) => { | ||
res.json(userData); | ||
try { | ||
const currentUser = await User.findById(currentUserId); | ||
const friendUser = await User.findById(friendUserId); | ||
|
||
if (!currentUser || !friendUser) { | ||
return res.status(404).send("One or both users not found"); | ||
} | ||
|
||
if (!currentUser.friends.includes(friendUserId)) { | ||
currentUser.friends.push(friendUserId); | ||
await currentUser.save(); | ||
console.log(`Added ${friendUserId} to ${currentUser.id}'s friends list.`); | ||
} else { | ||
return res.status(200).send("Already friends"); | ||
} | ||
|
||
if (!friendUser.friends.includes(currentUserId)) { | ||
friendUser.friends.push(currentUserId); | ||
await friendUser.save(); | ||
} | ||
|
||
res.status(200).send("Friends added successfully"); | ||
|
||
} catch (error) { | ||
console.error("Error in addFriend route:", error); | ||
res.status(500).send("Error adding friend"); | ||
} | ||
}); | ||
|
||
module.exports = router; | ||
module.exports = router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
const express = require("express"); | ||
const router = express.Router(); | ||
const { User } = require("../models/User.js"); | ||
|
||
router.get('/', async (req, res) => { | ||
const { username } = req.query; | ||
try { | ||
const userData = await User.findOne({ username: username }).select("username avatar _id"); | ||
if (!userData) { | ||
return res.status(404).send("User not found"); | ||
} | ||
res.json(userData); | ||
} catch (error) { | ||
res.status(500).json({ message: "Error accessing the database" }); | ||
} | ||
}); | ||
|
||
module.exports = router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,61 +1,103 @@ | ||
import React, { useState } from 'react'; | ||
import React, { useState, useEffect } from 'react'; | ||
import addFriendButton from "../images/plus-button.png"; | ||
import { jwtDecode } from 'jwt-decode'; | ||
|
||
function AddFriendModal({ showModal, onClose }) { | ||
const [userData, setUserData] = useState(null); | ||
const [loading, setLoading] = useState(false); | ||
const [error, setError] = useState(''); | ||
|
||
const backupUserData = { | ||
"avatar": "https://robohash.org/facerevoluptasconsequatur.png?size=50x50\u0026set=set1", | ||
"name": "Ulberto Crow" | ||
}; | ||
|
||
async function handleSearchClick() { | ||
setUserData(null); | ||
setError(''); | ||
setLoading(true); | ||
const username = document.querySelector('.input-content').value; | ||
try { | ||
const response = await fetch("http://localhost:3001/addFriends"); | ||
const response = await fetch(`http://localhost:3001/searchFriend?username=${username}`); | ||
if (!response.ok) { | ||
throw new Error(`HTTP error! Status: ${response.status}`); | ||
if (response.status === 404) { | ||
setError('User not found.'); | ||
} else { | ||
throw new Error(`HTTP error! Status: ${response.status}`); | ||
} | ||
} else { | ||
const data = await response.json(); | ||
setUserData(data); | ||
} | ||
const data = await response.json(); | ||
setUserData(data); | ||
} catch (error) { | ||
console.error("Error fetching data:", error); | ||
setError('Failed to fetch data. Please try again.'); | ||
setUserData(backupUserData); // Using the backup data on error | ||
} finally { | ||
setLoading(false); | ||
} | ||
} | ||
|
||
function addFriend(friendUserId) { | ||
const token = localStorage.getItem("token"); | ||
const currentUser = jwtDecode(token); | ||
|
||
if (!currentUser || !currentUser.id) { | ||
console.error("No current user found in local storage."); | ||
return; | ||
} | ||
|
||
if (currentUser.id === friendUserId) { | ||
setError("You cannot add yourself as a friend."); | ||
return; | ||
} | ||
|
||
fetch("http://localhost:3001/addFriends", { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ currentUserId: currentUser.id, friendUserId: friendUserId }), | ||
}) | ||
.then(response => { | ||
if (!response.ok) { | ||
throw new Error('Could not add friend'); | ||
} | ||
return response.text(); | ||
}) | ||
.then(message => { | ||
setError(message); | ||
}) | ||
.catch(error => { | ||
console.error("Error adding friend:", error); | ||
setError("Failed to add friend. Please try again."); | ||
}); | ||
} | ||
|
||
|
||
return ( | ||
<div className="modal"> | ||
<div className="modal-content"> | ||
<span className="close" onClick={onClose}>×</span> | ||
<h2>Add a new friend</h2> | ||
<input type="text" placeholder="Email or Phone" className='input-content'/> | ||
<input type="text" placeholder="Enter username" className='input-content'/> | ||
<button onClick={handleSearchClick}>Search</button> | ||
{loading && <div>Loading...</div>} | ||
{userData && ( | ||
<div className="add-friend-item"> | ||
<img src={userData.avatar} alt={`${userData.name}'s avatar`} className="friend-avatar"/> | ||
<span className="add-friend-name">{userData.name}</span> | ||
<img src={userData.avatar} alt={`avatar`} className="friend-avatar"/> | ||
<span className="add-friend-name">{userData.username}</span> | ||
<img | ||
src={addFriendButton} | ||
alt="Add friend" | ||
className="add-friend-button" | ||
style={{ width: "50px", height: "50px" }} | ||
onClick={() => addFriend(userData._id)} | ||
/> | ||
</div> | ||
)} | ||
{error && ( | ||
<div className="error-message"> | ||
{error} | ||
</div> | ||
)} | ||
</div> | ||
</div> | ||
); | ||
} | ||
|
||
export default AddFriendModal; | ||
|
||
export default AddFriendModal; |