From fd0bd852193ffdfcceafd3f634bf7f86d305fc2b Mon Sep 17 00:00:00 2001 From: Rykkel <220993G@mymail.nyp.edu.sg> Date: Mon, 12 Aug 2024 17:46:04 +0800 Subject: [PATCH] Filter post by a tag --- client/src/pages/CommunityPage.tsx | 61 +++++++++++++++++++++++++++++- server/routes/post.js | 7 ++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/client/src/pages/CommunityPage.tsx b/client/src/pages/CommunityPage.tsx index 746ab57..b1d4e19 100644 --- a/client/src/pages/CommunityPage.tsx +++ b/client/src/pages/CommunityPage.tsx @@ -66,6 +66,8 @@ export default function CommunityPage() { const [imageErrorFlags, setImageErrorFlags] = useState< Record >({}); + const [tags, setTags] = useState([]); + const [selectedTag, setSelectedTag] = useState(null); let accessToken = localStorage.getItem("accessToken"); if (!accessToken) { @@ -87,14 +89,44 @@ export default function CommunityPage() { } const getPosts = async () => { - await instance.get(config.serverAddress + "/post").then((res) => { + let query = config.serverAddress + "/post"; + if (selectedTag) { + query += `?tag=${selectedTag}`; + } else if (search) { + query += `?search=${search}`; + } + + try { + const res = await instance.get(query); setCommunityList(res.data); - }); + } catch (error) { + console.error("Error fetching posts:", error); + } }; useEffect(() => { getPosts(); + }, [selectedTag, search]); + + useEffect(() => { + const fetchTags = async () => { + try { + const res = await instance.get(config.serverAddress + "/post/tags/all"); + setTags(res.data); + } catch (error) { + console.error("Error fetching tags:", error); + } + }; + fetchTags(); }, []); + const handleTagClick = (tag: string) => { + setSelectedTag(tag); + }; + + const handleClearFilter = () => { + setSelectedTag(null); + }; + useEffect(() => { const fetchUserInformation = async (userId: string) => { try { @@ -134,6 +166,7 @@ export default function CommunityPage() { }; const searchPosts = () => { + setSelectedTag(null); // Clear tag filter on search instance .get(config.serverAddress + `/post?search=${search}`) .then((res) => { @@ -337,6 +370,30 @@ export default function CommunityPage() { } /> +
+

Filter by Tags

+
+ {tags.map((tag) => ( + handleTagClick(tag.tag)} + className={selectedTag === tag.tag ? "bg-primary-500 text-white" : ""} + > + {tag.tag} + + ))} +
+
+ {selectedTag && ( + + )} +
+
diff --git a/server/routes/post.js b/server/routes/post.js index 3f2f6bb..298b862 100644 --- a/server/routes/post.js +++ b/server/routes/post.js @@ -114,12 +114,19 @@ router.get("/", async (req, res) => { }; let search = req.query.search; + let tag = req.query.tag; + if (search) { condition.where[Op.or] = [ { title: { [Op.like]: `%${search}%` } }, { content: { [Op.like]: `%${search}%` } }, ]; } + + if (tag) { + condition.include[0].where = { tag: tag }; + } + // You can add condition for other columns here // e.g. condition.columnName = value;