Added Edit & Display Tags function

This commit is contained in:
Rykkel
2024-08-11 19:32:43 +08:00
parent 82fe2c4940
commit 0388a1e29e
6 changed files with 140 additions and 43 deletions

View File

@@ -1,10 +1,10 @@
import React, { useState } from "react";
import { Button, input } from "@nextui-org/react";
import { Button } from "@nextui-org/react";
import NextUIFormikTagInput from "./NextUIFormikTagInput";
type TagInputProps = {
tags: string[];
setTags: React.Dispatch<React.SetStateAction<string[]>>;
setTags: (tags: string[]) => void;
};
const TagInput: React.FC<TagInputProps> = ({ tags, setTags }) => {

View File

@@ -37,7 +37,7 @@ interface Post {
title: string;
postImage: Blob;
content: string;
tags: string;
Tags: Tag[];
id: string;
userId: string;
}
@@ -48,6 +48,11 @@ type User = {
lastName: string;
};
interface Tag {
id: string;
tag: string;
}
export default function CommunityPage() {
const navigate = useNavigate();
const { isOpen, onOpen, onOpenChange } = useDisclosure();
@@ -81,8 +86,8 @@ export default function CommunityPage() {
);
}
const getPosts = () => {
instance.get(config.serverAddress + "/post").then((res) => {
const getPosts = async () => {
await instance.get(config.serverAddress + "/post").then((res) => {
setCommunityList(res.data);
});
};
@@ -267,8 +272,13 @@ export default function CommunityPage() {
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-row gap-2">
<Chip>Tag 1</Chip>
<Chip>Tag 2</Chip>
{post.Tags.length > 0 ? (
post.Tags.map((tag) => (
<Chip key={tag.id}>{tag.tag}</Chip>
))
) : (
<p></p>
)}
</div>
<div className="flex flex-row">
<Button

View File

@@ -71,8 +71,7 @@ function CreatePostPage() {
if (values.postImage) {
formData.append("postImage", values.postImage);
}
// formData.append("tags", values.tags);
formData.append("tags", tags.join(","));
formData.append("tags", JSON.stringify(tags));
formData.append("userId", userId || ""); // Ensure userId is appended to formData
console.log("Submitting formData:", formData);

View File

@@ -10,6 +10,7 @@ import config from "../config";
import instance from "../security/http";
import { ArrowUTurnLeftIcon } from "../icons";
import InsertPostImage from "../components/InsertPostImage";
import TagInput from "../components/TagInput";
const validationSchema = Yup.object({
title: Yup.string()
@@ -36,6 +37,7 @@ const validationSchema = Yup.object({
function EditPostPage() {
const { id } = useParams();
const navigate = useNavigate();
const [tags, setTags] = useState<string[]>([]);
const [post, setPost] = useState({
title: "",
content: "",
@@ -45,27 +47,67 @@ function EditPostPage() {
const [loading, setLoading] = useState(true);
useEffect(() => {
instance.get(config.serverAddress + `/post/${id}`).then((res) => {
setPost({
...res.data,
postImage: `${config.serverAddress}/post/post-image/${id}`, // Set image URL
});
setLoading(false);
});
async function fetchPost() {
try {
const response = await instance.get(`${config.serverAddress}/post/${id}`);
const postData = response.data;
console.log("Fetched data: ", postData)
console.log("postData.tags data: ", postData.Tags);
if (postData && postData.Tags) {
// Adjust the structure according to the actual shape of tagObject
const postTags = postData.Tags.map((tagObject: any) => {
console.log("Tag Object: ", tagObject); // Debug each tagObject
return tagObject.tag; // Adjust according to actual key
});
setTags(postTags);
console.log("postTags:", postTags);
} else {
console.log("postData.Tags is not available or is undefined");
}
// Set the post data including other fields
setPost({
...postData,
postImage: postData.postImage ? `${config.serverAddress}/post/post-image/${id}` : null,
tags: tags,
});
} catch (error) {
console.error("Error fetching post data:", error);
} finally {
setLoading(false);
}
}
fetchPost();
}, [id]);
useEffect(() => {
console.log("Tags updated: ", tags);
}, [tags]);
const handleSubmit = async (
values: any,
{ setSubmitting, resetForm, setFieldError }: any
{ setSubmitting, resetForm, setFieldError, setFieldValue }: any
) => {
try {
const formData = new FormData();
formData.append("title", values.title);
formData.append("content", values.content);
if (values.postImage) {
// Append postImage only if it exists
console.log(values.postImage instanceof File); // Should be true if it's a File
if (values.postImage && values.postImage instanceof File) {
formData.append("postImage", values.postImage);
}
formData.append("tags", values.tags);
formData.append("tags", JSON.stringify(tags)); // This sends tags as a JSON string
console.log("Updating formData:", formData);
const response = await instance.put(
config.serverAddress + `/post/${id}`,
@@ -76,7 +118,8 @@ function EditPostPage() {
if (response.status === 200) {
console.log("Post updated successfully:", response.data);
resetForm();
// Set a flag to indicate a refresh is needed
setTags([]);
setFieldValue("postImage", null);
navigate(-1);
} else {
console.error("Error updating post:", response.statusText);
@@ -107,11 +150,11 @@ function EditPostPage() {
<section className="w-8/12 mx-auto p-5 bg-primary-100 border border-none rounded-2xl">
{!loading && (
<Formik
initialValues={post}
initialValues={{ ...post, tags: tags || [] }}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{({ isValid, dirty, isSubmitting, setFieldValue }) => (
{({ isValid, dirty, isSubmitting, setFieldValue, values }) => (
<Form className="flex flex-col gap-5">
<div>
<NextUIFormikInput
@@ -130,12 +173,12 @@ function EditPostPage() {
/>
</div>
<div>
<NextUIFormikInput
label="Tags (Optional)"
name="tags"
type="text"
placeholder="Enter tags"
labelPlacement="inside"
<TagInput
tags={tags}
setTags={(newTags) => {
setTags(newTags);
setFieldValue("tags", newTags); // Update Formik's state
}}
/>
</div>
<div className="text-sm">

View File

@@ -32,7 +32,7 @@ interface Post {
title: string;
postImage: Blob;
content: string;
tags: string;
Tags: Tag[];
id: string;
userId: string;
}
@@ -43,6 +43,11 @@ type User = {
lastName: string;
};
interface Tag {
id: string;
tag: string;
}
const PostPage: React.FC = () => {
const navigate = useNavigate();
const { id } = useParams<{ id: string }>();
@@ -207,8 +212,13 @@ const PostPage: React.FC = () => {
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-row gap-2">
<Chip>Tag 1</Chip>
<Chip>Tag 2</Chip>
{post.Tags.length > 0 ? (
post.Tags.map((tag) => (
<Chip key={tag.id}>{tag.tag}</Chip>
))
) : (
<p></p>
)}
</div>
<div className="flex flex-row">
<Button variant="light" isIconOnly>

View File

@@ -1,6 +1,6 @@
const express = require("express");
const router = express.Router();
const { Post, Comment, User } = require("../models");
const { Post, Comment, User, Tag, PostTag } = require("../models");
const { Op, where } = require("sequelize");
const yup = require("yup");
const multer = require("multer");
@@ -35,6 +35,7 @@ router.post(
async (req, res) => {
let data = req.body;
let files = req.files;
let tags = req.body.tags ? JSON.parse(req.body.tags) : [];
// Validate request body
let validationSchema = yup.object({
@@ -74,6 +75,15 @@ router.post(
// Process valid data
let result = await Post.create({ ...data, postImage });
// Handle tags
for (let tagName of tags) {
let [tag, created] = await Tag.findOrCreate({
where: { tag: tagName },
});
await result.addTag(tag); // Associate the tag with the post
}
res.json(result);
} catch (err) {
res.status(400).json({ errors: err.errors });
@@ -94,6 +104,13 @@ router.get("/", async (req, res) => {
let condition = {
where: {},
order: [["createdAt", "DESC"]],
include: [
{
model: Tag,
through: { attributes: [] }, // Exclude attributes from the join table
attributes: ["id", "tag"], // Fetch only 'id' and 'tag' attributes
},
],
};
let search = req.query.search;
@@ -112,7 +129,15 @@ router.get("/", async (req, res) => {
router.get("/:id", async (req, res) => {
let id = req.params.id;
let post = await Post.findByPk(id);
let post = await Post.findByPk(id, {
include: [
{
model: Tag,
through: { attributes: [] }, // Exclude attributes from the join table
attributes: ["id", "tag"], // Fetch only 'id' and 'tag' attributes
},
],
});
if (!post) {
res.sendStatus(404);
@@ -146,6 +171,8 @@ router.put(
async (req, res) => {
let id = req.params.id;
let files = req.files;
let data = req.body;
let tags = req.body.tags ? JSON.parse(req.body.tags) : [];
// Check id not found
let post = await Post.findByPk(id);
@@ -154,15 +181,13 @@ router.put(
return;
}
let data = req.body;
let postImage = files.postImage ? files.postImage[0].buffer : null;
// Validate request body
let validationSchema = yup.object({
title: yup.string().trim().min(3).max(100),
content: yup.string().trim().min(3).max(500),
title: yup.string().trim().min(3).max(200).required(),
content: yup.string().trim().min(3).max(500).required(),
postImage: yup.mixed(),
});
try {
data = await validationSchema.validate(data, { abortEarly: false });
@@ -179,6 +204,7 @@ router.put(
});
}
let postImage = files.postImage ? files.postImage[0].buffer : null;
// Include the postImage if present
if (postImage) {
postImage = await sharp(postImage)
@@ -192,11 +218,20 @@ router.put(
data.postImage = postImage;
}
// Process valid data
let post = await Post.update(data, {
// update() updates data based on the where condition, and returns the number of rows affected
where: { id: id }, // If num equals 1, return OK, otherwise return Bad Request
});
// Update post data
await post.update(data);
// Clear existing tags
await post.setTags([]);
// Handle tags
for (let tagName of tags) {
let [tag, created] = await Tag.findOrCreate({
where: { tag: tagName },
});
await post.addTag(tag); // Associate the tag with the post
}
if (post) {
res.json({ message: "Post was updated successfully." });
} else {