Skip to content

Commit

Permalink
[Feat] 좋아요 기능 피드페이지 디테일 페이지 구현 완료(#10)
Browse files Browse the repository at this point in the history
[Fix] 디테일 페이지 호출 에러(#56)
  • Loading branch information
nebulaBdj committed Dec 4, 2023
1 parent ebb1a6c commit 0e933f9
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 46 deletions.
35 changes: 25 additions & 10 deletions src/app/detail/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,25 @@ interface boardCommentType {
status: number;
}

interface LIKE {
likeId : number;
nickName: string;
}


export default function Detail(): JSX.Element {
const [boardDetail, setBoardDetail] = useState<any>(null);
const [dropdownVisible, setDropdownVisible] = useState<boolean>(false);
const [localBoardId, setLocalBoardId] = useState<number | null>(0);
const [localBoardId, setLocalBoardId] = useState<number | null | undefined>();
const [editBoardId, setEditBoardId] = useRecoilState(editBoardIdState);
const [comment, setComment] = useState<boardCommentType[]>([]);
const [likelist, setLikelist] = useState<LIKE[]>([]);//리코일로 만드는게 나을듯 일단은 이대로 ㄱㄱ
const [likeCount, setLikeCount] = useState<number>();

const router = useRouter();
console.log(router);
// console.log(router);
const accessToken = Cookies.get("accessToken");
console.log("accessToken 값: ", accessToken);
// console.log("accessToken 값: ", accessToken);

// const expirationTime = 3 * 60 * 60 * 1000;
// const currentTime = new Date().getTime();
Expand All @@ -59,36 +65,40 @@ export default function Detail(): JSX.Element {
? (jwt.decode(accessToken) as { [key: string]: any })
: null;
const decoded_nickName = decodedToken?.sub;
console.log("디코딩", decodedToken);
// console.log("디코딩", decodedToken);

useEffect(() => {
//여기서 localStorae의 값을 가져와 정수로 바꾸기
const boardId_in = localStorage.getItem("getBoardId_local");
const boardIdNumber = boardId_in ? parseInt(boardId_in) : null;
setLocalBoardId(boardIdNumber);

console.log("정수 변환", boardIdNumber);
console.log("로컬에서 불러온 아이디", localBoardId);
}, [localBoardId]);
// console.log("정수 변환", boardIdNumber);
// console.log("로컬에서 불러온 아이디", localBoardId);

useEffect(() => {
}, []);

useEffect(()=>{
const fetchData = async () => {
if (!localBoardId) return;
try {
const response = await axios.get(
`https://www.jerneithe.site/board/detail/${localBoardId}`,
);
console.log("detail response: ", response.data);
console.log("댓글: ", response.data.comments);
setLikelist(response.data.likelist);
setLikeCount(response.data.likeCount);
setBoardDetail(response.data);
setComment(response.data.comments);
console.log(response);
// console.log(response);
} catch (error) {
console.error("Error fetching data:", error);
}
};

fetchData();
}, [localBoardId]);
},[localBoardId, setLocalBoardId])

const handleClick = () => {
router.push("/");
Expand Down Expand Up @@ -120,6 +130,8 @@ export default function Detail(): JSX.Element {
}
};

console.log("보낼 좋아요 카운트와 리스트", likeCount, likelist);

return (
<div className="container flex flex-col items-center">
<header className="w-full">
Expand Down Expand Up @@ -194,6 +206,9 @@ export default function Detail(): JSX.Element {
<Like
boardId={localBoardId || 0}
accessToken={accessToken || ""}
nickname = {decoded_nickName}
likelist = {likelist}
likeCount = {likeCount}
/>
<CommentIcon
accessToken={accessToken}
Expand Down
2 changes: 1 addition & 1 deletion src/component/CommentIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface CommentIconProps {
accessToken: string | undefined;
boardComment: boardCommentType[];
decoded_nickName: string;
localBoardId: number | null;
localBoardId: number | null | undefined;
}

interface boardCommentType {
Expand Down
2 changes: 1 addition & 1 deletion src/component/CommentTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface CommentModalProps {
accessToken: string | undefined;
boardComment: boardCommentType[];
decoded_nickName: string;
localBoardId: number | null;
localBoardId: number | null | undefined;
}

interface boardCommentType {
Expand Down
15 changes: 11 additions & 4 deletions src/component/FeedContents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export default function FeedContents() {
likelist: isLiked
? myarr.likelist.filter((like) => like.nickName !== decodeNick)
: decodeNick // decodeNick이 undefined가 아닐 때만 추가
? [...myarr.likelist, { likeId: -1, nickName: decodeNick }]
? [...(Array.isArray(myarr.likelist) ? myarr.likelist : []), { likeId: -1, nickName: decodeNick }]
: myarr.likelist,
};
}
Expand Down Expand Up @@ -140,10 +140,17 @@ export default function FeedContents() {
router.push('/detail');
};

const isUserLiked = (likelist:LIKE[], userNickname:string | undefined) => {
// const isUserLiked = (likelist:LIKE[], userNickname:string | undefined) => {

// if (!likelist) return false;
// return likelist.some((like) => like.nickName === userNickname);
// // some: 위의 조건을 만족할 경우 순회를 중단 한다 즉, true 값을 리턴한다.
// // 만족 못한다면 false를 보냄
// };

const isUserLiked = (likelist:LIKE[] | undefined, userNickname:string | undefined) => {
if (!likelist || !Array.isArray(likelist)) return false;
return likelist.some((like) => like.nickName === userNickname);
// some: 위의 조건을 만족할 경우 순회를 중단 한다 즉, true 값을 리턴한다.
// 만족 못한다면 false를 보냄
};

console.log("리코일스테이트로 잘 들어왔는지 확인", feedata);
Expand Down
87 changes: 57 additions & 30 deletions src/component/Like.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,78 @@ import axios from "axios";
import Image from "next/image";
import { useEffect, useState } from "react";

interface LIKE {
likeId : number;
nickName: string;
}


export default function Like({
boardId,
accessToken,
nickname,
likelist,
likeCount,
}: {
boardId: number;
accessToken: string;
nickname: string;
likelist: LIKE[];
likeCount: number | undefined;
}): JSX.Element {
const [isLiked, setIsLiked] = useState(false);
const [likeCountState, setLikeCountState] = useState<number>(likeCount || 0);

// // boardId나 accessToken이 변경될 때 isLiked를 초기화
// useEffect(() => {
// setIsLiked(false);
// }, [boardId, accessToken]);

useEffect(()=>{
setIsLiked(isUserLiked(likelist, nickname));
},[]);

// boardId나 accessToken이 변경될 때 isLiked를 초기화
useEffect(() => {
setIsLiked(false);
}, [boardId, accessToken]);
const updateLikeStatus = async (boardId : number) => {
const url = `https://www.jerneithe.site/board/like/${boardId}`;

try {
await axios({
method: "post",
url: url,
headers: { Authorization: "Bearer " + accessToken },
});
} catch (error) {
console.error("좋아요 변경 실패:", error);
}
};

const isUserLiked = (likelist:LIKE[] | undefined, userNickname:string | undefined) => {
if (!likelist || !Array.isArray(likelist)) return false;
return likelist.some((like) => like.nickName === userNickname);
};

const handleLikeClick = async () => {
if (isLiked) {
// 좋아요 취소
try {
await axios({
method: "DELETE",
url: `https://www.jerneithe.site/board/like/${boardId}`,
headers: { Authorization: "Bearer " + accessToken },
});
setIsLiked(false);
} catch (error) {
console.error("좋아요 취소 실패:", error);
}
} else {
// 좋아요 추가
try {
await axios({
method: "post",
url: `https://www.jerneithe.site/board/like/${boardId}`,
headers: { Authorization: "Bearer " + accessToken },
});
setIsLiked(true);
} catch (error) {
console.error("좋아요 실패:", error);
}
try {
await updateLikeStatus(boardId);
setIsLiked(!isLiked);
setLikeCountState(isLiked ? likeCountState - 1 : likeCountState + 1);
} catch (error) {
console.error('좋아요 변경 실패:', error);
}
};

return (
<>
{isLiked ? (

<Image
src={isLiked ? "/images/like.svg" : "/images/unLike.svg"}
alt="좋아요"
width={20}
height={20}
onClick={handleLikeClick}
/>
<p>{likeCountState}</p>
{/* {isLiked ? (
<Image
src="/images/like.svg"
alt="like"
Expand All @@ -66,7 +93,7 @@ export default function Like({
style={{ marginRight: "3px" }}
onClick={handleLikeClick}
/>
)}
)} */}
</>
);
}

0 comments on commit 0e933f9

Please sign in to comment.