Added Edit & Display Tags function
This commit is contained in:
@@ -1,10 +1,10 @@
|
|||||||
import React, { useState } from "react";
|
import React, { useState } from "react";
|
||||||
import { Button, input } from "@nextui-org/react";
|
import { Button } from "@nextui-org/react";
|
||||||
import NextUIFormikTagInput from "./NextUIFormikTagInput";
|
import NextUIFormikTagInput from "./NextUIFormikTagInput";
|
||||||
|
|
||||||
type TagInputProps = {
|
type TagInputProps = {
|
||||||
tags: string[];
|
tags: string[];
|
||||||
setTags: React.Dispatch<React.SetStateAction<string[]>>;
|
setTags: (tags: string[]) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const TagInput: React.FC<TagInputProps> = ({ tags, setTags }) => {
|
const TagInput: React.FC<TagInputProps> = ({ tags, setTags }) => {
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ interface Post {
|
|||||||
title: string;
|
title: string;
|
||||||
postImage: Blob;
|
postImage: Blob;
|
||||||
content: string;
|
content: string;
|
||||||
tags: string;
|
Tags: Tag[];
|
||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
}
|
}
|
||||||
@@ -48,6 +48,11 @@ type User = {
|
|||||||
lastName: string;
|
lastName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
interface Tag {
|
||||||
|
id: string;
|
||||||
|
tag: string;
|
||||||
|
}
|
||||||
|
|
||||||
export default function CommunityPage() {
|
export default function CommunityPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
const { isOpen, onOpen, onOpenChange } = useDisclosure();
|
||||||
@@ -81,8 +86,8 @@ export default function CommunityPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const getPosts = () => {
|
const getPosts = async () => {
|
||||||
instance.get(config.serverAddress + "/post").then((res) => {
|
await instance.get(config.serverAddress + "/post").then((res) => {
|
||||||
setCommunityList(res.data);
|
setCommunityList(res.data);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -267,8 +272,13 @@ export default function CommunityPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<div className="flex flex-row gap-2">
|
<div className="flex flex-row gap-2">
|
||||||
<Chip>Tag 1</Chip>
|
{post.Tags.length > 0 ? (
|
||||||
<Chip>Tag 2</Chip>
|
post.Tags.map((tag) => (
|
||||||
|
<Chip key={tag.id}>{tag.tag}</Chip>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p></p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-row">
|
<div className="flex flex-row">
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -71,8 +71,7 @@ function CreatePostPage() {
|
|||||||
if (values.postImage) {
|
if (values.postImage) {
|
||||||
formData.append("postImage", values.postImage);
|
formData.append("postImage", values.postImage);
|
||||||
}
|
}
|
||||||
// formData.append("tags", values.tags);
|
formData.append("tags", JSON.stringify(tags));
|
||||||
formData.append("tags", tags.join(","));
|
|
||||||
formData.append("userId", userId || ""); // Ensure userId is appended to formData
|
formData.append("userId", userId || ""); // Ensure userId is appended to formData
|
||||||
|
|
||||||
console.log("Submitting formData:", formData);
|
console.log("Submitting formData:", formData);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import config from "../config";
|
|||||||
import instance from "../security/http";
|
import instance from "../security/http";
|
||||||
import { ArrowUTurnLeftIcon } from "../icons";
|
import { ArrowUTurnLeftIcon } from "../icons";
|
||||||
import InsertPostImage from "../components/InsertPostImage";
|
import InsertPostImage from "../components/InsertPostImage";
|
||||||
|
import TagInput from "../components/TagInput";
|
||||||
|
|
||||||
const validationSchema = Yup.object({
|
const validationSchema = Yup.object({
|
||||||
title: Yup.string()
|
title: Yup.string()
|
||||||
@@ -36,6 +37,7 @@ const validationSchema = Yup.object({
|
|||||||
function EditPostPage() {
|
function EditPostPage() {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const [tags, setTags] = useState<string[]>([]);
|
||||||
const [post, setPost] = useState({
|
const [post, setPost] = useState({
|
||||||
title: "",
|
title: "",
|
||||||
content: "",
|
content: "",
|
||||||
@@ -45,27 +47,67 @@ function EditPostPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
instance.get(config.serverAddress + `/post/${id}`).then((res) => {
|
async function fetchPost() {
|
||||||
setPost({
|
try {
|
||||||
...res.data,
|
const response = await instance.get(`${config.serverAddress}/post/${id}`);
|
||||||
postImage: `${config.serverAddress}/post/post-image/${id}`, // Set image URL
|
const postData = response.data;
|
||||||
});
|
console.log("Fetched data: ", postData)
|
||||||
setLoading(false);
|
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]);
|
}, [id]);
|
||||||
|
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
console.log("Tags updated: ", tags);
|
||||||
|
}, [tags]);
|
||||||
|
|
||||||
const handleSubmit = async (
|
const handleSubmit = async (
|
||||||
values: any,
|
values: any,
|
||||||
{ setSubmitting, resetForm, setFieldError }: any
|
{ setSubmitting, resetForm, setFieldError, setFieldValue }: any
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append("title", values.title);
|
formData.append("title", values.title);
|
||||||
formData.append("content", values.content);
|
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("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(
|
const response = await instance.put(
|
||||||
config.serverAddress + `/post/${id}`,
|
config.serverAddress + `/post/${id}`,
|
||||||
@@ -76,7 +118,8 @@ function EditPostPage() {
|
|||||||
if (response.status === 200) {
|
if (response.status === 200) {
|
||||||
console.log("Post updated successfully:", response.data);
|
console.log("Post updated successfully:", response.data);
|
||||||
resetForm();
|
resetForm();
|
||||||
// Set a flag to indicate a refresh is needed
|
setTags([]);
|
||||||
|
setFieldValue("postImage", null);
|
||||||
navigate(-1);
|
navigate(-1);
|
||||||
} else {
|
} else {
|
||||||
console.error("Error updating post:", response.statusText);
|
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">
|
<section className="w-8/12 mx-auto p-5 bg-primary-100 border border-none rounded-2xl">
|
||||||
{!loading && (
|
{!loading && (
|
||||||
<Formik
|
<Formik
|
||||||
initialValues={post}
|
initialValues={{ ...post, tags: tags || [] }}
|
||||||
validationSchema={validationSchema}
|
validationSchema={validationSchema}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
>
|
>
|
||||||
{({ isValid, dirty, isSubmitting, setFieldValue }) => (
|
{({ isValid, dirty, isSubmitting, setFieldValue, values }) => (
|
||||||
<Form className="flex flex-col gap-5">
|
<Form className="flex flex-col gap-5">
|
||||||
<div>
|
<div>
|
||||||
<NextUIFormikInput
|
<NextUIFormikInput
|
||||||
@@ -130,12 +173,12 @@ function EditPostPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<NextUIFormikInput
|
<TagInput
|
||||||
label="Tags (Optional)"
|
tags={tags}
|
||||||
name="tags"
|
setTags={(newTags) => {
|
||||||
type="text"
|
setTags(newTags);
|
||||||
placeholder="Enter tags"
|
setFieldValue("tags", newTags); // Update Formik's state
|
||||||
labelPlacement="inside"
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ interface Post {
|
|||||||
title: string;
|
title: string;
|
||||||
postImage: Blob;
|
postImage: Blob;
|
||||||
content: string;
|
content: string;
|
||||||
tags: string;
|
Tags: Tag[];
|
||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
}
|
}
|
||||||
@@ -43,6 +43,11 @@ type User = {
|
|||||||
lastName: string;
|
lastName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
interface Tag {
|
||||||
|
id: string;
|
||||||
|
tag: 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 }>();
|
||||||
@@ -207,8 +212,13 @@ const PostPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<div className="flex flex-row gap-2">
|
<div className="flex flex-row gap-2">
|
||||||
<Chip>Tag 1</Chip>
|
{post.Tags.length > 0 ? (
|
||||||
<Chip>Tag 2</Chip>
|
post.Tags.map((tag) => (
|
||||||
|
<Chip key={tag.id}>{tag.tag}</Chip>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p></p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-row">
|
<div className="flex flex-row">
|
||||||
<Button variant="light" isIconOnly>
|
<Button variant="light" isIconOnly>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
const express = require("express");
|
const express = require("express");
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const { Post, Comment, User } = require("../models");
|
const { Post, Comment, User, Tag, PostTag } = 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");
|
||||||
@@ -35,6 +35,7 @@ router.post(
|
|||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
let data = req.body;
|
let data = req.body;
|
||||||
let files = req.files;
|
let files = req.files;
|
||||||
|
let tags = req.body.tags ? JSON.parse(req.body.tags) : [];
|
||||||
|
|
||||||
// Validate request body
|
// Validate request body
|
||||||
let validationSchema = yup.object({
|
let validationSchema = yup.object({
|
||||||
@@ -74,6 +75,15 @@ router.post(
|
|||||||
|
|
||||||
// Process valid data
|
// Process valid data
|
||||||
let result = await Post.create({ ...data, postImage });
|
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);
|
res.json(result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(400).json({ errors: err.errors });
|
res.status(400).json({ errors: err.errors });
|
||||||
@@ -94,6 +104,13 @@ router.get("/", async (req, res) => {
|
|||||||
let condition = {
|
let condition = {
|
||||||
where: {},
|
where: {},
|
||||||
order: [["createdAt", "DESC"]],
|
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;
|
let search = req.query.search;
|
||||||
@@ -112,7 +129,15 @@ router.get("/", async (req, res) => {
|
|||||||
|
|
||||||
router.get("/:id", async (req, res) => {
|
router.get("/:id", async (req, res) => {
|
||||||
let id = req.params.id;
|
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) {
|
if (!post) {
|
||||||
res.sendStatus(404);
|
res.sendStatus(404);
|
||||||
@@ -146,6 +171,8 @@ router.put(
|
|||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
let files = req.files;
|
let files = req.files;
|
||||||
|
let data = req.body;
|
||||||
|
let tags = req.body.tags ? JSON.parse(req.body.tags) : [];
|
||||||
|
|
||||||
// Check id not found
|
// Check id not found
|
||||||
let post = await Post.findByPk(id);
|
let post = await Post.findByPk(id);
|
||||||
@@ -154,15 +181,13 @@ router.put(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = req.body;
|
|
||||||
let postImage = files.postImage ? files.postImage[0].buffer : null;
|
|
||||||
|
|
||||||
// Validate request body
|
// Validate request body
|
||||||
let validationSchema = yup.object({
|
let validationSchema = yup.object({
|
||||||
title: yup.string().trim().min(3).max(100),
|
title: yup.string().trim().min(3).max(200).required(),
|
||||||
content: yup.string().trim().min(3).max(500),
|
content: yup.string().trim().min(3).max(500).required(),
|
||||||
postImage: yup.mixed(),
|
postImage: yup.mixed(),
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
data = await validationSchema.validate(data, { abortEarly: false });
|
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
|
// Include the postImage if present
|
||||||
if (postImage) {
|
if (postImage) {
|
||||||
postImage = await sharp(postImage)
|
postImage = await sharp(postImage)
|
||||||
@@ -192,11 +218,20 @@ router.put(
|
|||||||
data.postImage = postImage;
|
data.postImage = postImage;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process valid data
|
// Update post data
|
||||||
let post = await Post.update(data, {
|
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
|
// 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) {
|
if (post) {
|
||||||
res.json({ message: "Post was updated successfully." });
|
res.json({ message: "Post was updated successfully." });
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
Reference in New Issue
Block a user