
//처음 초기값을 product.wishCheck을 통해서 받았다..!
const [wishCheck, setwishcheck] = useState(product.wishCheck);
useEffect(() => { // 상품 정보 axios
axios
.get(`https://i8c110.p.ssafy.io/api/v1/product/${productId}?userCode=2`)
.then((res) => {
setProduct(res.data);
setwishCnt(res.data.wishSize);
setwishcheck(res.data.wishCheck);
setliveReqSize(res.data.liveReqSize);
console.log(res.data, "🎇");
setproductImgs(res.data.imgUrlList);
})
.catch((err) => {
console.log(err);
});
}, []);
//좋아요를 클릭하면
<div className={styles.icon} onClick={addwish}>
// post 요청하기
const addwish = () => {
//wishcheck가 true라면 post 요청
if (wishCheck === false) {
axios
.post(`https://i8c110.p.ssafy.io/api/v1/wish?userCode=2&productId=${productId}`)
.then((res) => {
console.log(res, "🎉");
console.log(res.data.wishCheck, "🎈");
setwishcheck(res.data.wishCheck);
console.log(res.data.wishCnt, "🎆");
setwishCnt(res.data.wishCnt);
})
.catch((err) => {
console.log(err);
});
}
useState의 가장 큰 장점은 새로고침 하지 않아도 동적으로 최신 상태로 업데이트 시켜준다는 것이다..!
이 사실을 몰라서 useEffect 두번째 인자로 계속 넣고 있었다...
const [wishCnt, setwishCnt] = useState(product.wishSize);
useEffect(() => { // 상품 정보 axios
axios
.get(`https://i8c110.p.ssafy.io/api/v1/product/${productId}?userCode=2`)
.then((res) => {
setProduct(res.data);
setwishCnt(res.data.wishSize);
setwishcheck(res.data.wishCheck);
setliveReqSize(res.data.liveReqSize);
console.log(res.data, "🎇");
setproductImgs(res.data.imgUrlList);
})
.catch((err) => {
console.log(err);
});
}, []);
const addwish = () => {
//wishcheck가 true라면 post 요청
if (wishCheck === false) {
axios
.post(`https://i8c110.p.ssafy.io/api/v1/wish?userCode=2&productId=${productId}`)
.then((res) => {
console.log(res, "🎉");
console.log(res.data.wishCheck, "🎈");
setwishcheck(res.data.wishCheck);
console.log(res.data.wishCnt, "🎆");
setwishCnt(res.data.wishCnt);
})
.catch((err) => {
console.log(err);
});
}
//wishcheck가 true라면 delete요청
else {
axios
.delete(`https://i8c110.p.ssafy.io/api/v1/wish?userCode=2&productId=${productId}`)
.then((res) => {
console.log(res, "🎃");
setwishcheck(res.data.wishCheck);
setwishCnt(res.data.wishCnt);
})
.catch((err) => {
console.log(err);
});
}
};