Skip to content

Commit

Permalink
Merge pull request #133 from HungrySlugs-CSE115A/comment_section
Browse files Browse the repository at this point in the history
Fixed location page error when not logged in and removed comment edit ui
  • Loading branch information
IanHollow authored Jun 3, 2024
2 parents 46f92b7 + 25a7452 commit 33fa92f
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 90 deletions.
10 changes: 3 additions & 7 deletions app/locations/[location]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,9 @@ export default function Page({ params }: { params: { location: number } }) {

//get username and set it
let username = "";
try {
const userInfo = await fetchUserInfo();
username = userInfo.email ? userInfo.email : "anonymous";
//console.log("username is: ", username);
} catch (error) {
console.error("Failed to fetch user info:", error);
}
const userInfo = await fetchUserInfo();
username = userInfo.email;
//console.log("username is:", username);

fetchFoodReviewsBulk({
food_names: food_names,
Expand Down
11 changes: 6 additions & 5 deletions app/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function updateReview(data: {
return res.data;
}

export async function fetchUserInfo() {
export const fetchUserInfo = async () => {
try {
const access_token = sessionStorage.getItem("token");

Expand All @@ -62,7 +62,7 @@ export async function fetchUserInfo() {
"https://www.googleapis.com/oauth2/v3/userinfo",
{
headers: { Authorization: `Bearer ${access_token}` },
},
}
);

const userInfo = response.data;
Expand All @@ -73,7 +73,8 @@ export async function fetchUserInfo() {
picture: userInfo.picture,
};
} catch (error) {
console.error("Error fetching user info:", error);
throw error; // Re-throw the error so it can be handled by the calling code
return {
email: "anonymous",
};
}
}
};
108 changes: 42 additions & 66 deletions components/food/comments.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
"use client";
import { useEffect, useState } from "react";
import { Food, Comment } from "@/interfaces/Food";
import axios from "axios";
Expand All @@ -21,47 +20,45 @@ function pythonDatetimeToJsDatetime(pythonDatetime: string): Date {
export default function Comments({ food }: { food: Food }) {
const [comments, setComments] = useState<Comment[]>(food.comments);
const [textField, setTextField] = useState("");
const [user_id, setUserId] = useState("anonymous");
const [editIndex, setEditIndex] = useState<number | null>(null);
const [editTextField, setEditTextField] = useState("");
const [userId, setUserId] = useState("anonymous");
const [userInfoLoaded, setUserInfoLoaded] = useState(false); // Track if user info is loaded
//const [editIndex, setEditIndex] = useState<number | null>(null);
//const [editTextField, setEditTextField] = useState("");

useEffect(() => {
const getUserInfo = async () => {
try {
const userInfo = await fetchUserInfo();
const email = userInfo.email;
setUserId(email ? email : "anonymous");
} catch (error) {
console.error("Failed to fetch user info:", error);
}
const userInfo = await fetchUserInfo();
setUserId(userInfo.email);
setUserInfoLoaded(true); // Set to true
//console.log("comments userid:", userId);
};
getUserInfo(); // Call the function to fetch user info
}, []);
}, [userId]);

const postComment = (comment: {
const postComment = async (comment: {
food_name: string;
user_id: string;
comment: string;
}) => {
axios
.post("http://localhost:8000/api/comments/", comment)
.then((response) => {
const updatedFood: Food = response.data;
const updatedComments = updatedFood.comments;
setComments(updatedComments);
setTextField(""); // Clear the textarea after submission
})
.catch((error) => {
console.error(error);
});
if (!userInfoLoaded) return; // Ensure user info is loaded before posting

try {
const response = await axios.post("http://localhost:8000/api/comments/", comment);
const updatedFood: Food = response.data;
const updatedComments = updatedFood.comments;
setComments(updatedComments);
setTextField(""); // Clear the textarea after submission
} catch (error) {
console.error(error);
}
};

const editComment = (index: number) => {
/* const editComment = (index: number) => {
setEditIndex(index);
setEditTextField(comments[index].comment); // Set textarea value to the comment text
};
const saveEditedComment = (commentId: number) => {
const saveEditedComment = async (commentId: number) => {
const updatedComments = [...comments];
updatedComments[editIndex!].comment = editTextField; // Update the comment text
setComments(updatedComments);
Expand All @@ -74,19 +71,20 @@ export default function Comments({ food }: { food: Food }) {
comment: editTextField,
};
axios
.put(`http://localhost:8000/api/comments/${commentId}/`, editedComment)
.then((response) => {
console.log("Comment updated successfully:", response.data);
})
.catch((error) => {
console.error("Failed to update comment:", error);
});
};
try {
const response = await axios.put(`http://localhost:8000/api/comments/${commentId}/`, editedComment);
console.log("Comment updated successfully:", response.data);
} catch (error) {
console.error("Failed to update comment:", error);
}
}; */

return (
<div>
<div className="pt-5">
<h1 className="text-2xl text-[#003C6C] flex items-center justify-center py-3 mr-2 mb-1">
{food && food.name}
</h1>
<div>
{comments.map((comment, i) => (
<div
key={i}
Expand All @@ -99,42 +97,20 @@ export default function Comments({ food }: { food: Food }) {
<span className="text-gray-500 text-sm">
{pythonDatetimeToJsDatetime(comment.date).toLocaleString()}
</span>
{user_id === comment.user_id && (
{/* {userId === comment.user_id && (
<>
{editIndex !== i ? (
<button
onClick={() => editComment(i)}
className="mr-2 px-4"
>
Edit
</button>
<button onClick={() => editComment(i)} className="mr-2 px-4">Edit</button>
) : (
<>
<button
onClick={() => saveEditedComment(comments[i].id)}
className="ml-4 mr-2 px-2 py-1 bg-blue-500 text-white rounded-md"
>
Save
</button>
<button onClick={() => saveEditedComment(comments[i].id)} className="ml-4 mr-2 px-2 py-1 bg-blue-500 text-white rounded-md">Save</button>
<button onClick={() => setEditIndex(null)}>Cancel</button>
</>
)}
</>
)}
)} */}
</div>
<p className="px-2 break-words">
{editIndex !== i ? (
comment.comment
) : (
<input
type="text"
value={editTextField}
onChange={(e) => setEditTextField(e.target.value)}
className="w-full border border-gray-300 p-2 mb-2 mt-2 break-all max-w-full"
style={{ borderColor: "rgb(107, 114, 128)" }}
/>
)}
</p>
<p className="px-2 break-words">{comment.comment}</p>
</div>
))}
</div>
Expand All @@ -151,16 +127,16 @@ export default function Comments({ food }: { food: Food }) {
onClick={() =>
postComment({
food_name: food.name,
user_id: user_id,
user_id: userId,
comment: textField,
})
}
className={`ml-2 text-white ${
textField.length === 0
textField.length === 0 || !userInfoLoaded
? "bg-gray-300 cursor-default"
: "bg-blue-500 hover:bg-blue-700"
} rounded-md px-4 py-2`}
disabled={textField.length === 0}
disabled={textField.length === 0 || !userInfoLoaded}
>
Post
</button>
Expand Down
5 changes: 2 additions & 3 deletions components/food/images.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Food } from "@/interfaces/Food";
import ImageDisplay from "@/components/images_section/ImageDisplay"; // Import ImageDisplay component
import { fetchUserInfo } from "@/app/user_info"; // Import fetchUserInfo function
import { fetchUserInfo } from "@/app/requests";
import "@/components/food/Images.css"; // Import the CSS file

interface ImagesProps {
Expand Down Expand Up @@ -47,7 +46,7 @@ const Images: React.FC<ImagesProps> = ({ food }) => {
// Send image data to backend
const response = await axios.post(
"http://localhost:8000/api/upload_image/",
formData,
formData
);

// Log the response to debug
Expand Down
11 changes: 3 additions & 8 deletions components/location/categories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,9 @@ export default function LocationCategories({

useEffect(() => {
const getUserInfo = async () => {
try {
const userInfo = await fetchUserInfo();
const username = userInfo.email ? userInfo.email : "anonymous";
setUserId(username);
} catch (error) {
console.error("Failed to fetch user info:", error);
setUserId("anonymous");
}
//get username and set it
const userInfo = await fetchUserInfo();
setUserId(userInfo.email);
};
getUserInfo();
//console.log("userId =", userId);
Expand Down
Binary file modified db.sqlite3
Binary file not shown.
2 changes: 1 addition & 1 deletion interfaces/Food.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export interface Comment {
id: number;
// id: number;
user_id: string;
comment: string;
date: string;
Expand Down

0 comments on commit 33fa92f

Please sign in to comment.