For Programmer

12. 댓글 기능 생성(2) Comment.js 라우터 생성 - 유튜브 클론 코딩 본문

React & Node.js 프로젝트/유튜브 클론 코딩

12. 댓글 기능 생성(2) Comment.js 라우터 생성 - 유튜브 클론 코딩

유지광이 2020. 7. 26. 21:38
728x90

1.Comment.js페이지 코딩(axios통신 포함),(client-src-components-views-VideoDetailPage-Sections-Comment.js)

import React, { useState } from 'react';
import Axios from 'axios';
import { useSelector } from 'react-redux';

function Comment(props) {
  const videoId = props.postId;
  const [commentValue, setcommentValue] = useState('');
  const user = useSelector((state) => state.user);

  const handleChange = (event) => {
    setcommentValue(event.currentTarget.value);
  };

  const onsubmit = (event) => {
    event.preventDefault();
    const variables = {
      content: commentValue,
      writer: user.userData._id,
      postId: videoId,
    };
    Axios.post('/api/comment/saveComment', variables).then((response) => {
      if (response.data.success) {
        console.log(response.data.result);
      } else {
        alert('커멘트를 저장하지 못했습니다.');
      }
    });
  };
  return (
    <div>
      <br />
      <p>Replies</p>
      <hr />

      {/* Comment Lists */}

      {/* Root Comment Form */}

      <form style={{ display: 'flex' }} onSubmit={onsubmit}>
        <textarea
          style={{ width: '100%', borderRadius: '5px' }}
          onChange={handleChange}
          value={commentValue}
          placeholder="코멘트를 작성해 주세요"
        />
        <br />
        <button style={{ width: '20%', height: '52px' }} onClick={onsubmit}>
          Submit
        </button>
      </form>
    </div>
  );
}

export default Comment;

*단, props를 받기위해선 부모 페이지에서 videoId값을 넘겨주어야한다.(VideoDetailPage.js)

<Comment postId={videoId} />

2.서버에서 해당 댓글 데이터를 저장(server-routes-comment.js)

const express = require("express");
const router = express.Router();
const Comment = require("../models/Comment");

//=================================
//             Comments
//=================================

router.post("/saveComment", (req, res) => {
  const comment = new Comment(req.body);
  comment.save((err, comment) => {
    if (err) return res.json({ success: false, err });

    Comment.find({ _id: comment._id }) //저장 후 id를 이용하여 바로 해당 witer정보를 찾는다.
      .populate("writer")
      .exec((err, result) => {
        if (err) return res.json({ success: false, err });
        res.status(200).json({ success: true, result });
      });
  });
});
module.exports = router;

*routes를 새로생성했으면 index.js에서 꼭 api를 등록해주는것은 잊지말자!

app.use("/api/comment", require("./routes/comment"));

 

실행결과(console.log에 데이터를 서버로 보내고 다시 서버에서 프론쪽으로 해당데이터를 보냈음)

* 동영상 강의

 

 

728x90
Comments