• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Next.js 게시판 방금작성한 댓글

방금작성한 댓글

  • 이 주제에는 2개 답변, 2명 참여가 있으며 Marina2 년, 1 월 전에 전에 마지막으로 업데이트했습니다.
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 글쓴이
  • #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후에 글이 실시간으로 보이는게 안됩니다. 
    
    어떻게 접근해야 하는지 감이 안잡힙니다. 살려주세요
    
     
     
    #85647

    codingapple
    키 마스터
    `/api/comment/commentData?id=${props.parentid}` 로 get요청중인거 결과는 잘 가져오나 출력해봅시다
    #85657

    Marina
    참가자
    /api/comment/new.js 에 밑부분에 
    
    res.status(200).json(result); 전송을 안하고 있었어요. 
    
    해결되었습니다. 감사해요
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠