Retrieve username for post
This commit is contained in:
@@ -16,6 +16,7 @@ import {
|
|||||||
ModalFooter,
|
ModalFooter,
|
||||||
useDisclosure,
|
useDisclosure,
|
||||||
Spinner,
|
Spinner,
|
||||||
|
User,
|
||||||
} from "@nextui-org/react";
|
} from "@nextui-org/react";
|
||||||
import config from "../config";
|
import config from "../config";
|
||||||
import instance from "../security/http";
|
import instance from "../security/http";
|
||||||
@@ -28,7 +29,8 @@ import {
|
|||||||
XMarkIcon,
|
XMarkIcon,
|
||||||
} from "../icons";
|
} from "../icons";
|
||||||
import { useNavigate } from "react-router-dom";
|
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";
|
// import UserPostImage from "../components/UserPostImage";
|
||||||
|
|
||||||
interface Post {
|
interface Post {
|
||||||
@@ -37,17 +39,29 @@ interface Post {
|
|||||||
content: string;
|
content: string;
|
||||||
tags: string;
|
tags: string;
|
||||||
id: number;
|
id: number;
|
||||||
|
userId: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type User = {
|
||||||
|
id: number;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
};
|
||||||
|
|
||||||
export default function CommunityPage() {
|
export default function CommunityPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
||||||
|
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
||||||
|
const [communityList, setCommunityList] = useState<Post[]>([]);
|
||||||
|
const [search, setSearch] = useState(""); // Search Function
|
||||||
|
const [userInformation, setUserInformation] = useState<Record<number, User>>({});
|
||||||
|
|
||||||
let accessToken = localStorage.getItem("accessToken");
|
let accessToken = localStorage.getItem("accessToken");
|
||||||
if (!accessToken) {
|
if (!accessToken) {
|
||||||
return (
|
return (
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
navigate("/signin");
|
navigate("/signin");
|
||||||
}, 1000)
|
}, 1000)
|
||||||
&&
|
&&
|
||||||
<div className="flex justify-center items-center min-h-screen">
|
<div className="flex justify-center items-center min-h-screen">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
@@ -59,29 +73,40 @@ export default function CommunityPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
|
||||||
const [selectedPost, setSelectedPost] = useState<Post | null>(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<Post[]>([]);
|
|
||||||
|
|
||||||
// Search Function
|
|
||||||
const [search, setSearch] = useState("");
|
|
||||||
const onSearchChange = (e: { target: { value: SetStateAction<string> } }) => {
|
|
||||||
setSearch(e.target.value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const getPosts = () => {
|
const getPosts = () => {
|
||||||
instance.get(config.serverAddress + "/post").then((res) => {
|
instance.get(config.serverAddress + "/post").then((res) => {
|
||||||
setCommunityList(res.data);
|
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<string> } }) => {
|
||||||
|
setSearch(e.target.value);
|
||||||
|
};
|
||||||
|
|
||||||
const searchPosts = () => {
|
const searchPosts = () => {
|
||||||
instance
|
instance
|
||||||
.get(config.serverAddress + `/post?search=${search}`)
|
.get(config.serverAddress + `/post?search=${search}`)
|
||||||
@@ -90,10 +115,6 @@ export default function CommunityPage() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
getPosts();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const onSearchKeyDown = (e: { key: string }) => {
|
const onSearchKeyDown = (e: { key: string }) => {
|
||||||
if (e.key === "Enter") {
|
if (e.key === "Enter") {
|
||||||
searchPosts();
|
searchPosts();
|
||||||
@@ -108,13 +129,6 @@ export default function CommunityPage() {
|
|||||||
getPosts();
|
getPosts();
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
instance.get(config.serverAddress + "/post").then((res) => {
|
|
||||||
console.log(res.data);
|
|
||||||
setCommunityList(res.data);
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleDeleteClick = (post: Post) => {
|
const handleDeleteClick = (post: Post) => {
|
||||||
setSelectedPost(post);
|
setSelectedPost(post);
|
||||||
onOpen();
|
onOpen();
|
||||||
@@ -168,7 +182,7 @@ export default function CommunityPage() {
|
|||||||
<div className="flex flex-row justify-between">
|
<div className="flex flex-row justify-between">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<p className="text-xl font-bold">{post.title}</p>
|
<p className="text-xl font-bold">{post.title}</p>
|
||||||
<p className="text-md text-neutral-500">Adam</p>
|
<p className="text-md text-neutral-500">{userInformation[post.userId]?.firstName} {userInformation[post.userId]?.lastName}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-row-reverse justify-center items-center">
|
<div className="flex flex-row-reverse justify-center items-center">
|
||||||
<Dropdown>
|
<Dropdown>
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import NextUIFormikInput from "../components/NextUIFormikInput";
|
|||||||
import NextUIFormikTextarea from "../components/NextUIFormikTextarea";
|
import NextUIFormikTextarea from "../components/NextUIFormikTextarea";
|
||||||
import config from "../config";
|
import config from "../config";
|
||||||
import { ArrowUTurnLeftIcon } from "../icons";
|
import { ArrowUTurnLeftIcon } from "../icons";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { retrieveUserInformation } from "../security/users";
|
||||||
|
|
||||||
const validationSchema = Yup.object({
|
const validationSchema = Yup.object({
|
||||||
title: Yup.string()
|
title: Yup.string()
|
||||||
@@ -31,6 +33,7 @@ const validationSchema = Yup.object({
|
|||||||
|
|
||||||
function CreatePostPage() {
|
function CreatePostPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const [userId, setUserId] = useState(null);
|
||||||
|
|
||||||
const initialValues = {
|
const initialValues = {
|
||||||
title: "",
|
title: "",
|
||||||
@@ -38,12 +41,28 @@ function CreatePostPage() {
|
|||||||
tags: "",
|
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 (
|
const handleSubmit = async (
|
||||||
values: any,
|
values: any,
|
||||||
{ setSubmitting, resetForm, setFieldError }: any
|
{ setSubmitting, resetForm, setFieldError }: any
|
||||||
) => {
|
) => {
|
||||||
try {
|
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) {
|
if (response.status === 200) {
|
||||||
console.log("Post created successfully:", response.data);
|
console.log("Post created successfully:", response.data);
|
||||||
resetForm(); // Clear form after successful submit
|
resetForm(); // Clear form after successful submit
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
HandThumbsUpIcon,
|
HandThumbsUpIcon,
|
||||||
ArrowUTurnLeftIcon,
|
ArrowUTurnLeftIcon,
|
||||||
} from "../icons";
|
} from "../icons";
|
||||||
|
import { retrieveUserInformationById } from "../security/usersbyid";
|
||||||
|
|
||||||
interface Post {
|
interface Post {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -31,23 +32,49 @@ interface Post {
|
|||||||
content: string;
|
content: string;
|
||||||
tags: string;
|
tags: string;
|
||||||
id: number;
|
id: number;
|
||||||
|
userId: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type User = {
|
||||||
|
id: number;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
};
|
||||||
|
|
||||||
const PostPage: React.FC = () => {
|
const PostPage: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
const [post, setPost] = useState<Post | null>(null);
|
const [post, setPost] = useState<Post | null>(null);
|
||||||
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
||||||
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
||||||
|
const [userInformation, setUserInformation] = useState<Record<number, User>>({});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (id) {
|
if (id) {
|
||||||
instance.get(`${config.serverAddress}/post/${id}`).then((res) => {
|
instance.get(`${config.serverAddress}/post/${id}`)
|
||||||
setPost(res.data);
|
.then((res) => setPost(res.data))
|
||||||
});
|
.catch((error) => console.error("Error fetching post:", error));
|
||||||
}
|
}
|
||||||
}, [id]);
|
}, [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) {
|
if (!post) {
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-center min-h-screen">
|
<div className="flex justify-center min-h-screen">
|
||||||
@@ -104,7 +131,7 @@ const PostPage: React.FC = () => {
|
|||||||
<div className="flex flex-row justify-between">
|
<div className="flex flex-row justify-between">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<p className="text-xl font-bold">{post.title}</p>
|
<p className="text-xl font-bold">{post.title}</p>
|
||||||
<p className="text-md text-neutral-500">Adam</p>
|
<p className="text-md text-neutral-500">{userInformation[post.userId]?.firstName} {userInformation[post.userId]?.lastName}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-row-reverse justify-center items-center">
|
<div className="flex flex-row-reverse justify-center items-center">
|
||||||
<Dropdown>
|
<Dropdown>
|
||||||
|
|||||||
17
client/src/security/usersbyid.ts
Normal file
17
client/src/security/usersbyid.ts
Normal file
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,9 +17,14 @@ module.exports = (sequelize, DataTypes) => {
|
|||||||
content: {
|
content: {
|
||||||
type: DataTypes.TEXT,
|
type: DataTypes.TEXT,
|
||||||
allowNull: false
|
allowNull: false
|
||||||
}
|
},
|
||||||
|
userId: {
|
||||||
|
type: DataTypes.UUID,
|
||||||
|
allowNull: false,
|
||||||
|
},
|
||||||
}, {
|
}, {
|
||||||
tableName: 'posts'
|
tableName: 'posts'
|
||||||
});
|
});
|
||||||
|
|
||||||
return Post;
|
return Post;
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const { Post } = require('../models');
|
const { Post, User } = require('../models');
|
||||||
const { Op, where } = require("sequelize");
|
const { Op, where } = require("sequelize");
|
||||||
const yup = require("yup");
|
const yup = require("yup");
|
||||||
const multer = require("multer");
|
const multer = require("multer");
|
||||||
@@ -56,7 +56,10 @@ router.post("/", async (req, res) => {
|
|||||||
// });
|
// });
|
||||||
|
|
||||||
router.get("/", async (req, res) => {
|
router.get("/", async (req, res) => {
|
||||||
let condition = {};
|
let condition = {
|
||||||
|
order: [['createdAt', 'DESC']]
|
||||||
|
};
|
||||||
|
|
||||||
let search = req.query.search;
|
let search = req.query.search;
|
||||||
if (search) {
|
if (search) {
|
||||||
condition[Op.or] = [
|
condition[Op.or] = [
|
||||||
@@ -67,11 +70,7 @@ router.get("/", async (req, res) => {
|
|||||||
// You can add condition for other columns here
|
// You can add condition for other columns here
|
||||||
// e.g. condition.columnName = value;
|
// e.g. condition.columnName = value;
|
||||||
|
|
||||||
let list = await Post.findAll({
|
let list = await Post.findAll(condition);
|
||||||
where: condition,
|
|
||||||
// order option takes an array of items. These items are themselves in the form of [column, direction]
|
|
||||||
order: [['createdAt', 'DESC']]
|
|
||||||
});
|
|
||||||
res.json(list);
|
res.json(list);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user