diff --git a/client/src/pages/CommunityPage.tsx b/client/src/pages/CommunityPage.tsx index fffe686..56a8857 100644 --- a/client/src/pages/CommunityPage.tsx +++ b/client/src/pages/CommunityPage.tsx @@ -16,6 +16,7 @@ import { ModalFooter, useDisclosure, Spinner, + User, } from "@nextui-org/react"; import config from "../config"; import instance from "../security/http"; @@ -28,7 +29,8 @@ import { XMarkIcon, } from "../icons"; import { useNavigate } from "react-router-dom"; -// import { retrieveUserInformation } from "../security/users"; +import { retrieveUserInformationById } from "../security/usersbyid"; +import { number } from "yup"; // import UserPostImage from "../components/UserPostImage"; interface Post { @@ -37,17 +39,29 @@ interface Post { content: string; tags: string; id: number; + userId: number; } +type User = { + id: number; + firstName: string; + lastName: string; +}; + export default function CommunityPage() { const navigate = useNavigate(); - + const { isOpen, onOpen, onOpenChange } = useDisclosure(); + const [selectedPost, setSelectedPost] = useState(null); + const [communityList, setCommunityList] = useState([]); + const [search, setSearch] = useState(""); // Search Function + const [userInformation, setUserInformation] = useState>({}); + let accessToken = localStorage.getItem("accessToken"); if (!accessToken) { return ( setTimeout(() => { navigate("/signin"); - }, 1000) + }, 1000) &&
@@ -59,29 +73,40 @@ export default function CommunityPage() { ); } - const { isOpen, onOpen, onOpenChange } = useDisclosure(); - const [selectedPost, setSelectedPost] = useState(null); - - // const [userInformation, setUserInformation] = useState(null); - - // communityList is a state variable - // function setCommunityList is the setter function for the state variable - // e initial value of the state variable is an empty array [] - // After getting the api response, call setCommunityList() to set the value of CommunityList - const [communityList, setCommunityList] = useState([]); - - // Search Function - const [search, setSearch] = useState(""); - const onSearchChange = (e: { target: { value: SetStateAction } }) => { - setSearch(e.target.value); - }; - const getPosts = () => { instance.get(config.serverAddress + "/post").then((res) => { setCommunityList(res.data); }); }; + useEffect(() => { + getPosts(); + }, []); + + useEffect(() => { + const fetchUserInformation = async (userId: number) => { + try { + const user = await retrieveUserInformationById(userId); + setUserInformation((prevMap) => ({ + ...prevMap, + [userId]: user, + })); + } catch (error) { + console.error(error); + } + }; + + communityList.forEach((post) => { + if (!userInformation[post.userId]) { + fetchUserInformation(post.userId); + } + }); + }, [communityList]); + + const onSearchChange = (e: { target: { value: SetStateAction } }) => { + setSearch(e.target.value); + }; + const searchPosts = () => { instance .get(config.serverAddress + `/post?search=${search}`) @@ -90,10 +115,6 @@ export default function CommunityPage() { }); }; - useEffect(() => { - getPosts(); - }, []); - const onSearchKeyDown = (e: { key: string }) => { if (e.key === "Enter") { searchPosts(); @@ -108,13 +129,6 @@ export default function CommunityPage() { getPosts(); }; - useEffect(() => { - instance.get(config.serverAddress + "/post").then((res) => { - console.log(res.data); - setCommunityList(res.data); - }); - }, []); - const handleDeleteClick = (post: Post) => { setSelectedPost(post); onOpen(); @@ -168,7 +182,7 @@ export default function CommunityPage() {

{post.title}

-

Adam

+

{userInformation[post.userId]?.firstName} {userInformation[post.userId]?.lastName}

diff --git a/client/src/pages/CreatePostPage.tsx b/client/src/pages/CreatePostPage.tsx index b23593c..4d7a97e 100644 --- a/client/src/pages/CreatePostPage.tsx +++ b/client/src/pages/CreatePostPage.tsx @@ -7,6 +7,8 @@ import NextUIFormikInput from "../components/NextUIFormikInput"; import NextUIFormikTextarea from "../components/NextUIFormikTextarea"; import config from "../config"; import { ArrowUTurnLeftIcon } from "../icons"; +import { useEffect, useState } from "react"; +import { retrieveUserInformation } from "../security/users"; const validationSchema = Yup.object({ title: Yup.string() @@ -31,6 +33,7 @@ const validationSchema = Yup.object({ function CreatePostPage() { const navigate = useNavigate(); + const [userId, setUserId] = useState(null); const initialValues = { title: "", @@ -38,12 +41,28 @@ function CreatePostPage() { tags: "", }; + useEffect(() => { + const getUserInformation = async () => { + try { + const user = await retrieveUserInformation(); // Get the user ID + setUserId(user.id); // Set the user ID in the state + } catch (error) { + console.error(error); + } + }; + getUserInformation(); + }, []); + const handleSubmit = async ( values: any, { setSubmitting, resetForm, setFieldError }: any ) => { try { - const response = await axios.post(config.serverAddress + "/post", values); // Assuming an API route + const postData = { + ...values, + userId: userId + } + const response = await axios.post(config.serverAddress + "/post", postData); // Assuming an API route if (response.status === 200) { console.log("Post created successfully:", response.data); resetForm(); // Clear form after successful submit diff --git a/client/src/pages/PostPage.tsx b/client/src/pages/PostPage.tsx index bcc7079..152e358 100644 --- a/client/src/pages/PostPage.tsx +++ b/client/src/pages/PostPage.tsx @@ -24,6 +24,7 @@ import { HandThumbsUpIcon, ArrowUTurnLeftIcon, } from "../icons"; +import { retrieveUserInformationById } from "../security/usersbyid"; interface Post { title: string; @@ -31,23 +32,49 @@ interface Post { content: string; tags: string; id: number; + userId: number; } +type User = { + id: number; + firstName: string; + lastName: string; +}; + const PostPage: React.FC = () => { const navigate = useNavigate(); const { id } = useParams<{ id: string }>(); const [post, setPost] = useState(null); const { isOpen, onOpen, onOpenChange } = useDisclosure(); const [selectedPost, setSelectedPost] = useState(null); + const [userInformation, setUserInformation] = useState>({}); useEffect(() => { if (id) { - instance.get(`${config.serverAddress}/post/${id}`).then((res) => { - setPost(res.data); - }); + instance.get(`${config.serverAddress}/post/${id}`) + .then((res) => setPost(res.data)) + .catch((error) => console.error("Error fetching post:", error)); } }, [id]); + useEffect(() => { + if (post) { + const fetchUserInformation = async () => { + try { + const user = await retrieveUserInformationById(post.userId); + setUserInformation((prevMap) => ({ + ...prevMap, + [post.userId]: user, + })); + } catch (error) { + console.error(error); + } + }; + + fetchUserInformation(); + } + }, [post]); + if (!post) { return (
@@ -104,7 +131,7 @@ const PostPage: React.FC = () => {

{post.title}

-

Adam

+

{userInformation[post.userId]?.firstName} {userInformation[post.userId]?.lastName}

diff --git a/client/src/security/usersbyid.ts b/client/src/security/usersbyid.ts new file mode 100644 index 0000000..3ccd3d8 --- /dev/null +++ b/client/src/security/usersbyid.ts @@ -0,0 +1,17 @@ +import { AxiosError } from "axios"; +import config from "../config"; +import instance from "./http"; + +export async function retrieveUserInformationById(userId: number) { + if (!localStorage.getItem("accessToken")) { + throw "No access token"; + } + try { + let userInformation = await instance.get( + `${config.serverAddress}/users/individual/${userId}` + ); + return userInformation.data; + } catch (error) { + throw ((error as AxiosError).response?.data as any).message; + } +} \ No newline at end of file diff --git a/server/models/Post.js b/server/models/Post.js index 3f0df11..57712cc 100644 --- a/server/models/Post.js +++ b/server/models/Post.js @@ -17,9 +17,14 @@ module.exports = (sequelize, DataTypes) => { content: { type: DataTypes.TEXT, allowNull: false - } + }, + userId: { + type: DataTypes.UUID, + allowNull: false, + }, }, { tableName: 'posts' }); + return Post; } \ No newline at end of file diff --git a/server/routes/post.js b/server/routes/post.js index df5c495..fbe3efd 100644 --- a/server/routes/post.js +++ b/server/routes/post.js @@ -1,6 +1,6 @@ const express = require('express'); const router = express.Router(); -const { Post } = require('../models'); +const { Post, User } = require('../models'); const { Op, where } = require("sequelize"); const yup = require("yup"); const multer = require("multer"); @@ -56,7 +56,10 @@ router.post("/", async (req, res) => { // }); router.get("/", async (req, res) => { - let condition = {}; + let condition = { + order: [['createdAt', 'DESC']] + }; + let search = req.query.search; if (search) { condition[Op.or] = [ @@ -67,11 +70,7 @@ router.get("/", async (req, res) => { // You can add condition for other columns here // e.g. condition.columnName = value; - let list = await Post.findAll({ - where: condition, - // order option takes an array of items. These items are themselves in the form of [column, direction] - order: [['createdAt', 'DESC']] - }); + let list = await Post.findAll(condition); res.json(list); });