inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

따라하며 배우는 노드, 리액트 시리즈 - 유튜브 사이트 만들기

댓글 기능 생성 (3) SingleComment

에러를 해결 못하겠습니다

267

새우좋아하새우?

작성한 질문수 2

0

 

댓글 작성 후 submit을 누르면 이런 에러가 뜨는데 이유를 모르겠습니다. 

댓글 목록도 가져오지 못하는 것 같습니다 .ㅠㅠ 이유를 알 수 있을까요? ㅠㅠ

 

 

routes/comment.js

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

//=================================
//           Comment
//=================================

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})
        .populate('writer')
        .exec((err,result)=>{
            if(err) return res.json({success: false, err})
            res.status(200).json({success: true,result})
        })

    })
})

router.post('/getComments',(req,res)=>{

    Comment.find({"postId":req.body.videoid})
    .populate('writer')
    .exec((err,comments)=>{
        if(err) return res.status(400).send(err)
        res.status(200).json({success:true,comments})
    })
})



module.exports = router;

comment.js

import React, { useState } from 'react'
import axios from 'axios'
import {useSelector} from 'react-redux';
import SingleComment from './Singlecomment'


function Comment(props) {


  const videoId = props.postId
  const user=useSelector(state=>state.user); //redux/state/user 경로
  const [commentValue,setcommentValue]=useState("")
  const handleClick=(event)=>{

    setcommentValue(event.currentTarget.value)

  }

  const onSubmit=(event)=>{
    event.preventDefault();

    const variable={
      content:commentValue,
      writer:user.userData._id,
      postId:videoId
    }
    axios.post('/api/comment/saveComment',variable)
    .then(response=>{
      if(response.data.success){
        console.log(response.data.result)
        setcommentValue("")
        props.refreshFunction(response.data.result)
      }else{
        alert('코멘트를 저장하지 못했습니다.')
      }
    })

  }
  return (
    <div>
        <br />
        <p> Replies </p>
        <hr />
        {console.log(props.commentLists)}
        {props.commentLists && props.commentLists.map((comment, index) => (
          (!comment.responseTo &&
          <SingleComment refreshFunction={props.refreshFunction} comment={comment} postId={videoId} />
          )
        ))}

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

export default Comment

VideoDetailPage.js

import React, { useEffect,useState } from 'react'
import {Row,Col,List,Avatar} from 'antd'
import { FaLaughSquint } from 'react-icons/fa'
import Axios from 'axios'
//import { post } from '../../../../../server/routes/video'
//import { response } from 'express'
import SideVideo from './Sections/SideVideo'
import Subscribe from './Sections/Subscribe'
import Comment from './Sections/Comment'

function VideoDetailPage(props) {


    //const [Comments,setComment]=useState(initialState)

    const videoId=props.match.params.videoId
    const variable={videoId: videoId}

    const [VideoDetail,setVideoDetail]=useState([])
    const [Comments,setComments]=useState([])

    useEffect(()=>{
        Axios.post('/api/video/getVideoDetail',variable)
        .then(response=>{
            if(response.data.success){
                setVideoDetail(response.data.videoDetail)
            }else{
                alert('비디오 정보 가져오기 실패')
            }
        })

        Axios.post('/api/comment/getComments', variable)
        .then(response=>{
            if(response.data.success){
                setComments(response.data.Comments)
            }else{
                alert('코멘트 정보 가져오기 실패')
            }
        })
    }, [])

    const refreshFunction=(newComment)=>{
        setComments(Comments.concat(newComment))
    }

    if(VideoDetail.writer){

        const subscribeButton = VideoDetail.writer._id!==localStorage.getItem('userId') &&  <Subscribe userTo={VideoDetail.writer._id} userFrom={localStorage.getItem('userId')}/>

        return (
            <Row gutter={[16,16]}>
                <Col lg={18} xs={24}>
       
                <div style={{width:'100%',padding:'3rem 4rem'}}>
                    <video style={{width:'100%'}} src={`http://localhost:5000/${VideoDetail.filePath}`} controls/>
       
                    <List.Item
                        actions={[subscribeButton]}
                    >
                        <List.Item.Meta
                            avatar={<Avatar src={VideoDetail.writer.image}/>}
                            title={VideoDetail.writer.name}
                            description={VideoDetail.description}
                        />
                    </List.Item>

                    <Comment refreshFunction={refreshFunction} commentLists={Comments} postId={videoId}/>
       
       
                </div>
       
                </Col>
                <Col lg={6} sx={24}>
                    <SideVideo/>
                </Col>
            </Row>
            //</div>
          )
        }else{
            return(
        <div>...loading</div>
            )
    }
}

export default VideoDetailPage

nodejs mongodb react redux

답변 1

0

John Ahn

안녕하세요   우선 Comments.concat() 하실 때  Comments에 올바른 형식의 데이터가 안들어 있을 것 같습니다.  console.log로 Comments State를 먼저 확인해주세요 ~ 감사합니다.

0

새우좋아하새우?

정말 감사합니다! 에러 해결했어요😀!

npm i하면 바로, 라이브러리 오류없이 받아지고, 구동되는 소스는 없나요?

0

64

1

ERROR in ./node_modules/antd/es/version/index.js 2:15-22

0

230

1

자료 없음

0

339

1

이미지 깨짐

0

359

1

npm run dev 동작 에러

0

317

1

npm run dev 동작 에러

0

304

1

npm run dev 동작에러납니다...

0

670

1

npm run dev 실행 오류

0

665

1

비디오 업로드, 로그인, 회원가입 504 error

0

1065

1

시작부터 오류생기시는 분들 해결법입니다.

1

480

1

오류 해결 공유

0

479

1

npm install 에러 질문드립니다.

0

1144

2

아예 몽고DB에 연결한다고만 하고 연결이 안되고 있습니다.

0

558

1

해당 오류 해결 방법 좀 알려주세요 ㅠㅠ

0

545

1

로컬스토리지에 대한 질문입니다!!

0

523

0

video가 안 나타나는 문제

0

906

1

ffmpeg 설치 후 cannot read property 'format' of undefined 500 에러 해결

0

485

0

typeError or 콘솔 500 뜨는분..

0

346

0

npm run dev 관련 오류

0

587

1

답글이 달리지않고 디비에도 저장되지않으며 새로고침이 됩니다.

0

255

0

useState 자동 생성

0

351

1

TypeError: Cannot read properties of undefined (reading 'format')

0

1259

2

userData undefined / state에 user.userData가 없습니다.

0

254

0

antd Input background color 변경

0

248

0