react-query : Mutation, QueryClient 사용

김태영·2023년 6월 17일
0

현재 진행중인 쇼핑몰 프로젝트에 react-query 를 적용했는데, 일단 급하게 useQuery만을
사용하여 data를 fetching 하는데만 react-query를 사용하고 있었다.

오늘 공부한 Mutation과 queryClient를 내 코드에 적용시켜 보자.

queryClient와, Mutation을 적용, 리팩토링할 코드를 찾다가 아주 좋은 예시를 발견했다

리뷰등록 (수정 전)

 const handleReviewSubmit = useCallback(
    async (rating: number, comment: string) => {
      try {
        const response = await api.post(`/cal/v1/review/${id}`, {
          rating: rating,
          reviewText: comment,
        });
        const newReview = response.data; // Assuming the API returns the created review object

        setReviewList((prevReviewList) => [...prevReviewList, newReview]); // Update the review list in Recoil state
        getProductDetail();
      } catch (error) {
        if (axios.isAxiosError(error))
          handleOpenErrorModal(error.response?.data.message);
      }
    },
    [id, setReviewList]
  );

현재 react-query로 fetching을 해오고 있으나 react의 hooks 만을 이용해 이벤트를 처리하니
이벤트 발생후 데이터 동기화, 최신화가 매끄럽지 않게 이루어지고 있었다.

Mutation

반면에, mutation을 사용하게 되면 데이터를 변경시키고,
해당데이터를 동기화 할 때 유용하기에 mutation으로 코드를 수정하기로 결정했다.

리뷰등록 (수정 후)

const addReviewMutation = useMutation(
    async (reviewData: { rating: number; reviewText: string }) => {
      const response = await api.post(`/cal/v1/review/${id}`, reviewData);
      return response.data;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries(["productdetail"]);
      },
    }
  );
const handleReviewSubmit = useCallback(
    async (rating: number, comment: string): Promise<void> => {
      try {
        await addReviewMutation.mutateAsync({ rating, reviewText: comment });
      } catch (error) {
        if (axios.isAxiosError(error))
          handleOpenErrorModal(error.response?.data.message);
      }
    },
    []
  );

위와 같이 코드를 바꾸었고, mutation 함수 실행후 성공했을 때 queryClient를 사용한다.

queryClient

queryClient.invalidateQueries(["productdetail"]);

이 코드는 "productdetail" 이라는 키값을 가진 useQuery의 쿼리를 무효화 시켜
다시 실행하게끔 만들어 데이터를 다시 가져오게 되는것이다.

동일한 방식으로 리뷰댓글기능도 수정

리뷰 댓글기능(수정 전)

const handleCommentSubmit = async (id: number) => {
    // 댓글 등록 처리
    try {
      await api.post(`/cal/v1/review/comment/${id}`, {
        reviewCommentText: comment,
      });
      getProductDetail();
    } catch (error: any) {
      console.log(error);
    }
  };

리뷰 댓글기능(수정 후)

const addReviewCommentMutation = useMutation(
    async (commentData: { reviewCommentText: string; commentId: number }) => {
      const response = await api.post(
        `/cal/v1/review/comment/${commentData.commentId}`,
        commentData
      );
      return response.data;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries(["productdetail"]);
      },
    }
  );

  const handleCommentSubmit = useCallback(
    async (commentId: number) => {
      try {
        await addReviewCommentMutation.mutateAsync({
          reviewCommentText: comment,
          commentId: commentId,
        });
      } catch (error) {
        if (axios.isAxiosError(error))
          handleOpenErrorModal(error.response?.data.message);
      }
    },
    [comment]
  );

아직 완벽하게 이해하지 못해 프로젝트 중간점검? 중간 리팩토링을 통해 이해도를 높여야 할것같다.

PROJECT GITHUB LINK

profile
구렁이

0개의 댓글