choigirang / why-chat

아왜진 커뮤니티 미니 프로젝트
https://fe.why-chat.site
0 stars 0 forks source link

useMutation 댓글 업데이트 #16

Open choigirang opened 10 months ago

choigirang commented 7 months ago
/**
 * 댓글 추가 hooks
 * @param src 데이터 설정 post인지 gallery인지
 * @param id 게시글 number
 * @param data 댓글에 대한 데이터(작성자, 날짜 등)
 * @returns
 */
export function useAddComment(src: string, id: number, data: CommentAPI) {
  // src에 따른 fetch 함수
  async function fetchComment() {
    const response = await api.post(src === 'post' ? '/post/comment' : '/gallery/comment', data);
    return response.data;
  }

  return useMutation(src === 'post' ? ['post', id] : ['gallery', id], fetchComment, {
    onSuccess: () => {
      queryClient.invalidateQueries(src === 'post' ? ['post', id] : ['gallery', id]);
    },
  });
}

/** 댓글 추가하기 */
export default function AddComment({ number, author, src }: { number: number; author: string; src: string }) {
  // 작성된 댓글 데이터
  const [content, setContent] = useState('');

  // 날짜 지정
  const { dateHandler } = usePostForm();

  const user = useSelector((state: RootState) => state.user.user);

  // src에 따른 데이터 설정
  const postData = { postNumber: number, author, comment: content, date: dateHandler() };
  const galleryData = { galleryNumber: number, author, comment: content, date: dateHandler() };

  // src에 따른 comment 데이터 저장 위치 설정
  const { mutate } = useAddComment(src, number, src === 'post' ? postData : galleryData);

  // comment 추가 및 초기화
  const addComment = () => {
    mutate();
    setContent('');
  };

  return (
    <Container>
      <textarea
        rows={4} // 원하는 행의 수를 지정합니다.
        value={content}
        onChange={e => setContent(e.target.value)}
      />
      <button onClick={addComment} disabled={!user.login}>
        제출
      </button>
    </Container>
  );
}