today,weekly I learn

tanstack-query. 낙관적 업데이트

rhdaud2 2024. 7. 13. 01:13

 

 

댓글 기능 구현 중, 작성과 수정 시에 화면에 바로 적용이 될 때가 있고 새로고침해야 적용 될 때가 있어서

낙관적 업데이트 적용해봤음

 

기존 mutation 코드

  const addMutation = useMutation({
    mutationFn: addComment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['comments', postId] });
      setTargetValue({ title: '', content: '' });
      toast.success('작성 완료');
    },
    onError: () => {
      toast.error('작성중 오류 발생. 잠시 후 다시 시도해주세요');
    }
  });
  
  
    const updateMutation = useMutation({
    mutationFn: updateComment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['comments', postId] });
      setIsEdit(false);
      setTargetValue((prev) => ({ ...prev, title: '', content: '' }));
      toast.success('수정 완료');
    },
    onError: () => {
      toast.error('댓글 수정 중 오류가 발생했습니다.');
    }
  });

 

 

낙관적 업데이트 적용

  const addMutation = useMutation({
    mutationFn: addComment,
    onMutate: async (newComment) => {
      await queryClient.cancelQueries({ queryKey: ['comments', postId] });

      const previousComments = queryClient.getQueryData(['comments', postId]);

      queryClient.setQueryData(['comments', postId], (old: any) => [...(old || []), { ...newComment }]);

      setTargetValue({ title: '', content: '' });
      return { previousComments };
    },
    onError: (err, newComment, context) => {
      queryClient.setQueryData(['comments', postId], context?.previousComments);
      toast.error('작성중 오류 발생. 잠시 후 다시 시도해주세요');
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['comments', postId] });
      toast.success('작성 완료');
    }
  });

  const updateMutation = useMutation({
    mutationFn: updateComment,
    onMutate: async (updatedComment) => {
      await queryClient.cancelQueries({ queryKey: ['comments', postId] });

      const previousComments = queryClient.getQueryData(['comments', postId]);

      queryClient.setQueryData(['comments', postId], (old: any) =>
        old.map((comment: any) => (comment.id === updatedComment.id ? updatedComment : comment))
      );

      setIsEdit(false);
      setTargetValue({ title: '', content: '' });
      return { previousComments };
    },
    onError: (err, updatedComment, context) => {
      queryClient.setQueryData(['comments', postId], context?.previousComments);
      toast.error('댓글 수정 중 오류가 발생했습니다.');
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['comments', postId] });
      toast.success('수정 완료');
    }
  });

 

사용자 경험적으로 성능이 크게 증가한 것이 확인 가능했다

 

 

 

'today,weekly I learn' 카테고리의 다른 글

24.07.17  (0) 2024.07.17
24.07.16.최종 프로젝트 기획 회의 진행  (0) 2024.07.16
24.7.9  (0) 2024.07.09
무한스크롤(useInfiniteQuery,react-intersection-observer)  (0) 2024.07.07
tanstack query - 페이지네이션  (1) 2024.07.05