반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

Mutation 본문

인프런, 유데미/React-Query

Mutation

5_hyun 2023. 3. 30. 00:26

Mutation

mutation은 서버에 데이터를 업데이트하도록 서버에 네트워크 호출을 하는 것이다. 데이터를 추가, 수정, 삭제할 때 사용된다. 그렇기에 mutation을 활용하면 optimistic update를 구현할 수 있고, 쿼리 캐시를 업데이트할 수 있으며 클라이언트에 있는 데이터를 최신 상태로 유지할 수 있다.

useMutation

useMutation은 useQuery와 비슷하다. 하지만 데이터를 저장하지 않아 key는 필요가 없다. 그리고 isLoading은 있지만 데이터를 저장하지 않으니까 캐시 된 항목이 없어서 isFetching은 없다. 기본값으로 재시도는 하지 않지만 설정할 수 있다.  

사용법

블로그 댓글을 삭제하는 예시이다.

  const deleteMutation = useMutation((postId) => deletePost(postId));

useMutation을 활용하여 댓글을 삭제해준다.

      <button onClick={() => deleteMutation.mutate(post.id)}>Delete</button>
      {deleteMutation.isError && (
        <p style={{ color: "red" }}>Error deleting the post</p>
      )}
      {deleteMutation.isLoading && (
        <p style={{ color: "purple" }}>Deleting the post</p>
      )}
      {deleteMutation.isSuccess && <p style={{ color: "green" }}>Success</p>}

버튼에서 post.id를 줘서 댓글을 삭제할 수 있다. 그리고 isError, isLoading, isSuccess를 활용하여 현재 상태도 표시해 줄 수 있다.

728x90
반응형
Comments