프론트엔드 개발자가 될거야./react
[1차 프로젝트] 상세페이지에 리뷰기능 추가하기
정니정은니
2022. 7. 31. 23:12
르주르 베이비 세트
르주르
www.le-jour.com
클론코딩한 Magazine B의 상세페이지에는 리뷰기능이 없다.
그래서 이 사이트의 리뷰기능을 참고하여
Magazine B의 상세페이지에 리뷰기능을 추가구현하기로 했다.
이렇게 상세페이지 아래에 추가될 예정! 이었지만…
눈에 띄는 더 큰 별점이 있었으면 좋겠어서
이렇게 수정하기로 했다.
내가 디자인하고 내가 개발하는 거라 혼자 내린 결론이다. ㅎㅎ
어차피 back에게는 선택한 별점이 몇인지, 무슨 리뷰를 달았는지만 전달해주면 되기 때문이다.
back과의 통신이 세 번 필요하다.
이 리뷰기능을 구현하면서 통신을 세 번이나 했는데 이를 통해 백엔드와의 통신의 중요성을 뼈저리게 느낄 수 있었다.
2차 프로젝트를 위해 fetch와 then으로 백과 통신하는 법을 확실하게 공부해 두어야겠다.
(1) Productdetail.js에서 상세페이지에 대한 api
useEffect(() => {
fetch(`http://10.58.4.114:8000/products/${product_id}`)
.then(res => res.json())
.then(data => {
setPrdDetailData([data.RESULTS]);
});
}, []);
(2) Review.js에서 review데이터를 받아오는 api
import { useParams } from 'react-router-dom';
let { product_id } = useParams();
useEffect(() => {
fetch(`http://10.58.4.114:8000/products/${product_id}/reviews`)
.then(res => res.json())
.then(data => {
setReviewData(data.RESULTS);
});
}, []);
(3) Review.js에서 별점을 선택하고 리뷰를 작성했을 때 버튼을 누르면 POST해주는 api
const addReview = e => {
if (commentText.length < 6) {
alert('5글자 이상을 입력해주세요');
setCommentText('');
} else if (rating === 0) {
alert('별점을 선택해주세요.');
} else {
const textareaObj = {
username: 'aa11',
content: commentText,
rating: rating,
};
const copyComment = [...comment, textareaObj];
setComment(copyComment);
const addReview = e => {
if (commentText.length < 6) {
alert('5글자 이상을 입력해주세요');
setCommentText('');
} else if (rating === 0) {
alert('별점을 선택해주세요.');
} else {
const textareaObj = {
username: 'aa11',
content: commentText,
rating: rating,
};
fetch(`http://10.58.3.49:8000/products/${product_id}/reviews`, {
//사용할 http 메소드
method: 'POST',
//토큰
headers: {
Authorization: token,
},
//서버에 보낼 데이터 (별점, 리뷰)
body: JSON.stringify({
rating: rating,
content: commentText,
}),
})
.then(res => res.json())
.then(data => {
if (data.MESSAGE === 'SUCCESS') {
const copyComment = [...comment, textareaObj];
setComment(copyComment);
setCommentText('');
window.location.reload();
} else {
alert('구매하셔야 리뷰등록 가능합니다!');
setCommentText('');
}
});
}
};
back에게 받은 data 가공하기 (너무 힘들다! ㅎ ㅡ ㅎ)
리뷰기능을 구현하기 위해서는 reviews 데이터가 필요하다.
이 데이터로 map을 돌려 댓글을 구현해야하기 때문이다.
또한 이 데이터에 유저가 추가한 별점과 댓글을 추가해야한다.
const [comment, setComment] = useState([]);
const [reviewData, setReviewData] = useState([]);
useEffect(() => {
setComment(reviewData);
}, [reviewData]);
useEffect(() => {
fetch(`http://10.58.3.49:8000/products/${product_id}/reviews`)
.then(res => res.json())
.then(data => {
setReviewData(data.RESULTS);
});
}, []);
이렇게 back에게 받아온 데이터를
useEffect와 useState를 활용하여 만질 수 있다.
back의 데이터 + 유저가 추가할 데이터를 합쳐
<div className="commentBox">
{comment.map((data, i) => {
return <Comment key={i} data={data} />;
})}
</div>
이렇게 map을 돌리면 댓글이 추가된다.