꾸준하게 거북이처럼

refactor : useMuate의 mutateAsync 사용해서 비동기 함수로 이벤트 이후 부분 처리하기 본문

개인공부/React

refactor : useMuate의 mutateAsync 사용해서 비동기 함수로 이벤트 이후 부분 처리하기

somm12 2023. 6. 27. 15:28

고민했던 것

useMutate를 이용해서 자동으로 댓글 업데이트가 되도록 구현을 했지만, 이후에 '댓글 수정이 완료되었습니다!' alert같은 이벤트 이후 처리 부분을 어떻게 할지 고민했다.

해결한 방법

useMutate에서 제공하는 isSuccess를 이용해서 useEffect로 이후 처리를 했다.

하지만 이 방법은 먼가 코드가 깔끔하지 않았다.. 

더 찾아보니 mutateAsync 를 제공해서 이걸 사용하여 이벤트가 발생하면, 비동기 처리함수로 이후 동작을 처리할 수 있을 것 같았다.

개선해보기✨

이전 코드

  const {
    mutate: editMutate,
    isSuccess: isEditSuccess,
    isError: isEditError,
  } = useEditComment(comment.postId, user.uid, newComment, comment._id);
  
// 댓글 수정 완료 여부 확인 및 업데이트.
 useEffect(() => {
    if (isEditSuccess) {
      alert("댓글 수정 완료가 되었습니다!!");
      setNewComment("");
      setEditFlag(false);
      return;
    }
    if (isDeleteError) {
      alert("댓글 수정에 실패했습니다!!");
    }
  }, [isEditSuccess]);
  
   const submitEditHandler =  (e) => {
    e.preventDefault();
    if (!newComment) {
      alert("댓글을 작성해주세요!");
    }
    editMuate();
   }

개선한 코드

  const {
    mutateAsync: editMutateAsync
  } = useEditComment(comment.postId, user.uid, newComment, comment._id); // useMutation반환.

const submitEditHandler = async (e) => {
    e.preventDefault();
    if (!newComment) {
      alert("댓글을 작성해주세요!");
    }

     try {
      const {
        data: { success },
      } = await editMutateAsync();
      if (success) {
        setNewComment("");
        setEditFlag(false);
        alert("댓글 수정이 완료되었습니다!");
      }
    } catch (error) {
      alert("댓글 수정에 실패했습니다!");
    }
  };

개선한 코드가 훨씬 가독성도 좋아서 이 방향으로 코드를 수정하고자 한다.

Comments