3 글 보임 - 1 에서 3 까지 (총 3 중에서)
-
글쓴이글
-
2023년 6월 2일 16:10 #85625
Marina참가자//detail/[id]/comment.js
"use client"; import React, { useEffect, useState } from "react";
export default function Comment(props) { let [comment, setComment] = useState(""); let [commentList, setCommentList] = useState([]);
const fetchComments = () => { fetch(`/api/comment/commentData?id=${props.parentid}`) .then((r) => r.json()) .then((result) => { setCommentList(result); }); };
useEffect(() => { fetchComments(); }, []);
return ( <div> <textarea onChange={(e) => { setComment(e.target.value); }} /> <button onClick={() => { fetch("/api/comment/new", { method: "POST", body: JSON.stringify({ comment: comment, parentid: props.parentid, }), }) .then((r) => r.json()) .then((result) => { console.log(result); fetchComments(); // 코멘트를 저장한 후에 코멘트 리스트를 다시 가져옵니다. }); }} > 전송 </button>
<div> {commentList.map((a, i) => { return ( <div key={i}> <span className="mr-5">{a.authorName}</span> <span>{a.content}</span> </div> ); })} </div> </div> ); }
// pages/api/auth/comment/commentData.js
import { connectDB } from "@/util/database"; import { ObjectId } from "mongodb";
export default async function handler(req, res) { const db = (await connectDB).db("forum"); const result = await db .collection("comment") .find({ parentId: new ObjectId(req.query.id) }) .toArray(); res.status(200).json(result); }
// pages/api/auth/comment/new.js
import { getServerSession } from "next-auth"; import { authOptions } from "../auth/[...nextauth]"; import { connectDB } from "@/util/database"; import { ObjectId } from "mongodb";
export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (session) { if (req.method == "POST") { req.body = JSON.parse(req.body); const db = (await connectDB).db("forum"); const result = await db.collection("comment").insertOne({ content: req.body.comment, author: new ObjectId(session.user._id), authorName: session.user.name, parentId: new ObjectId(req.body.parentid), }); } } else { return res.status(400).json("로그인해라"); } console.log(req.body); }
저장도 잘되고 다른 문제는 없는데 onClick후에 글이 실시간으로 보이는게 안됩니다.
어떻게 접근해야 하는지 감이 안잡힙니다. 살려주세요
2023년 6월 2일 20:11 #85647
codingapple키 마스터`/api/comment/commentData?id=${props.parentid}` 로 get요청중인거 결과는 잘 가져오나 출력해봅시다
-
글쓴이글
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
- 답변은 로그인 후 가능합니다.