import React, { useEffect, useState } from "react";
import Axios from "axios";
function Subscribe(props) {
const [SubscriberNumber, setSubscriberNumber] = useState(0);
const [Subscribed, setSubscribed] = useState(false);
useEffect(() => {
let variables = { userTo: props.userTo };
Axios.post("/api/subscribe/subscriberNumber", variables).then(
(response) => {
if (response.data.success) {
setSubscriberNumber(response.data.subscriberNumber);
} else {
alert("구독자수를 확인하는데 실패했습니다.");
}
}
);
let subscribedVariables = {
userTo: props.userTo,
userFrom: localStorage.getItem("userId"),
};
Axios.post("/api/subscribe/subscribed", subscribedVariables).then(
(response) => {
if (response.data.success) {
setSubscribed(response.data.subscribed);
} else {
alert("구독했는지 확인하지 못했습니다.");
}
}
);
}, []);
const onSubscribe = () => {
let subscribeVariables = {
userTo: props.userTo,
userFrom: props.userFrom,
};
if (Subscribed) {
Axios.post("/api/subscribe/unSubscribe", subscribeVariables).then(
(response) => {
if (response.data.success) {
setSubscribed(!Subscribed);
setSubscriberNumber(SubscriberNumber - 1);
} else {
alert("구독취소를 실패했습니다.");
}
}
);
} else {
Axios.post("/api/subscribe/subscribe", subscribeVariables).then(
(response) => {
if (response.data.success) {
setSubscribed(!Subscribed);
setSubscriberNumber(SubscriberNumber + 1);
} else {
alert("구독을 실패했습니다.");
}
}
);
}
};
return (
<div
style={{
backgroundColor: `${Subscribed ? "#AAAAAA" : "#CC0000"}`,
borderRadius: "4px",
color: "white",
padding: "10px 16px",
fontWeight: "500",
fontSize: "1rem",
textTransform: "uppercase",
}}
onClick={onSubscribe}
>
{Subscribed ? "Subscribed" : `${SubscriberNumber} Subscribe`}
</div>
);
}
export default Subscribe;
1.전 VideoDetailPage.js에서 Subscriber 컴포넌트에 props로 _id를 넘길 때 writer의 _id를 넘겨야 하는데 video의 _id를 넘기고 있더라구요. 다음과 같이 수정했습니다.