4 글 보임 - 1 에서 4 까지 (총 4 중에서)
-
글쓴이글
-
2023년 5월 7일 18:54 #81466
권명찬참가자'use client'
import { useEffect, useState } from "react"
export default function Comment(props) { let [comment, setComment] =useState('') let [data, setData] = useState([])
useEffect(()=> { fetch('/api/comment/list?id=' + props._id).then(r => r.json()) .then((result) =>{ setData(result) }) },[]) return ( <div className='flex flex-col'> <div className='mb-3'>댓글 보여줄 부분</div> { data.length > 0 ? data.map((a,i)=>{ return ( <p key={i} className="mb-2">{a.author_name} : {a.content}</p> ) }) : '로딩중' } <input className='bg-white border-2 border-red-200 mb-3' onChange={(e)=>{ setComment(e.target.value)}} /> <button onClick={()=>{ fetch('/api/comment/new', { method : 'POST', body : JSON.stringify({comment : comment, _id : props._id}) }).then(res => res.json()) .then(newComment => { setData([...data, newComment]) setComment('') }) }} className='mb-3'>댓글전송</button> </div> ) } 안녕하세요 선생님
강의를 듣고 추가 공부도중에 name을 넣는건까지 했고
button에 onClick했을때
<button onClick={()=>{ fetch('/api/comment/new', { method : 'POST', body : JSON.stringify({comment : comment, _id : props._id}) }).then(res => res.json()) .then(newComment => { setData([...data, newComment]) setComment('') }) }}
에 then을 붙여서 작업을 하긴했는데 맨위의 사진과 같이 " : " 만 나와버려서
고민을 해보니 data로는 작업이 들어갔으나 useEffect에서 받는게 느려서 데이터가 늦게 나오는게 아닐까 싶은데
고민해보다가 몽고db가 오류가 난김에 질문글을 남겨봅니다 ㅠㅠㅠ
2023년 5월 9일 14:14 #81954
권명찬참가자안녕하세요 선생님
.then(res => { setData(prevData => [...prevData, res]) console.log(res) console.log(data) }) }}
을 보내고
api/comment/new 에서 응답.status(200).json(저장할거) 을 보내서
데이터가 제대로 들어오는걸 확인하고 맨위처럼 작업을 완료했더니
새로고침도 제대로 되고 db에도 정상업데이트 되는걸 확인했습니다만
궁금한점이 있는데
setData(prevData => [...prevData, res]) console.log(res) console.log(data)
에서 console을 두개 찍으면 마지막 data에는 업뎃이 됐어야 되는게 아닌가 싶은데
왜 res 부분은 추가가 되지않고 console에 이전꺼만 찍히는지 잘모르겠어서
제가 어느부분을 따로 검색해서 공부하면되는지 의견을 여쭈고자 답글 남깁니다
-
글쓴이글
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
- 답변은 로그인 후 가능합니다.