정리하기
진짜 저번주부터 리액트쿼리 mutation 찾아보고 고치느라 힘들었는데... 댓글 삭제로 3일동안 고생햇는데 바보같이 에러도 제대로 안 읽어본 게 문제였다ㅜㅜㅜ 콘솔창을 봣더니 id가 없고 map을 쓸 수 없다고 하셧는데 DetailPost data는 객체고 그 안에 comments 배열인데 내가 객체 취급했다..!
const deleteComment = ({ postId, commentId, t }) => {
return commentApi.deleteComment(postId, commentId, t);
};
const { mutateAsync } = useMutation(deleteComment);
const handleDeleteComment = async (commentId) => {
// isOk('댓글을 삭제하시겠습니까?') &&
try {
const result = await mutateAsync({ postId, commentId, t });
queryClient.setQueryData(['Detail', postId], (old) => ({
...old,
// 으여기 comments: old.comments.filter(...)
...old.comments.filter((comment) => comment.id !== commentId),
}));
// Detail을 invalidate 시키지만 refetch 하지 않음
// queryClient.invalidateQueries({
// queryKey: ['Detail', postId],
// refetchActive: false,
// });
} catch (error) {
console.log('deleteComment error', error);
}
};
글고 mutateAsync -> async 로 바꾸고, useMutation 에서 onSuccess, onError,.. 로 처리하기
const DetailPost = () => {
const t = useT();
const user = useUser();
const history = useHistory();
const boardType = history.location.pathname.split('/')[2];
const postId = history.location.pathname.split('/')[3];
const boardTitle = getBoardTitle(boardType);
const queryClient = useQueryClient(); // vs QueryClient
// 서버의데이터를불러와서동기화
const { isLoading, data, error, isError } = useDetailPost(postId);
// useEffect(() => {
// if (error) {
// // 백엔드에서 서버가바쁩니다 응답메시지
// // toast.error(`Something went wrong: ${error.message}`);
// }
// }, [error]);
const toHtml = (markdown) => marked.parse(markdown);
const { mutate: dd } = useSendComment();
const handleSendComment = async (commentInput, clear) => {
dd({ postId, data, t, clear });
// if (!user) {
// isOk('로그인 하시겠습니까?') && history.push('/login');
// return;
// }
// if (commentInput.trim().length < 2) {
// alert('댓글은 2자 이상 입력해주세요.');
// return;
// }
// const data = { content: commentInput };
// try {
// const result = await sendCommentMutate({ postId, data, t });
// console.log('handleSendComment result', result);
// queryClient.invalidateQueries(['Detail', postId]);
// clear();
// } catch (error) {
// console.log('handleSendComment error', error);
// } finally {
// console.log('done');
// }
};
// deleteComment
const deleteComment = ({ postId, commentId, t }) => {
return commentApi.deleteComment(postId, commentId, t);
};
// mutate - 서버에요청날리고기다리지않음 프로미스를반환하지않음
// mutateAsync - onSuccess가끝날때까지기다림
const { mutate } = useMutation(deleteComment, {
onSuccess: (data, variables, context) => {
queryClient.setQueryData(['Detail', postId], (old) => ({
...old,
comments: old.comments.filter(
(comment) => comment.id !== variables.commentId
),
}));
},
});
const handleDeleteComment = async (commentId) => {
mutate({ postId, commentId, t });
// if (isOk('댓글을 삭제하시겠습니까?'))
// try {
// // const result = await mutateAsync({ postId, commentId, t });
// // const data = queryClient.getQueryData(['Detail', postId]);
// // Detail을 invalidate 시키지만 refetch 하지 않음
// // queryClient.invalidateQueries({
// // queryKey: ['Detail', postId],
// // refetchActive: false,
// // });
// } catch (error) {
// console.log('deleteComment error', error);
// }
};
return !isLoading ? (
<>
<BoardTitle>{boardTitle}</BoardTitle>
<DetailContainer>
<div>
<Top isCurrentUser={Boolean(user)} data={data} />
<Content>
{data?.content ? parse(toHtml(data?.content)) : '로딩 중입니다!'}
</Content>
<Bottom
title={data?.title}
content={data?.content}
likes={data?.likes}
isPostUser={+user?.id === +data?.memberId}
/>
</div>
<CommentInfo
comments={data?.comments}
commentSize={data?.commentSize}
isSelected={data?.selected}
isPostUser={+user?.id === +data?.memberId}
handleSendComment={handleSendComment}
handleDeleteComment={handleDeleteComment}
/>
</DetailContainer>
</>
) : (
<div>loading...</div>
);
};
export default DetailPost;