React Query - Mutation

Code_Alpacat·2022년 10월 20일
0

Mutation

Mutation은 데이터를 읽는게 아닌 변경하는 로직에 대한 내용이다.
CREATE UPDATE, DELETE의 역할을 수행한다.

useMutation의 특징

  • mutate 함수를 반환한다.
  • 캐싱할 필요가 없으므로 쿼리 키를 사용하지 않는다.
  • 캐시가 존재하지 않으므로, isFetching이 없다.
  • retry를 3회 시도하는 useQuery와는 다르게 retry가 일어나지 않는다. 만약 retry로 실패시 재시도하려면, 설정이 필요하다

사용법

  • 기본적으로 useQuery와 같이 isLoading등이 존재하므로, 충돌을 피하기 위해 구조분해할당을 피해야할 경우가 있다.
  • mutate메서드를 통해 인자를 받을 수 있다.
import { useQuery, useMutation } from "@tanstack/react-query";

async function deletePost(postId) {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/postId/${postId}`,
    { method: "DELETE" }
  );
  return response.json();
}


//isLoading 등 이미 선언된 요소들과의 충돌을 피함.
const deleteMutation = useMutation((postId) => deletePost(postId));

//jsx
return (
    <>
      <h3 style={{ color: "blue" }}>{post.title}</h3>
      <button onClick={() => deleteMutation.mutate(post.id)}>
        Delete
      </button>
      {deleteMutation.isError && <p>에러로 인해 지우지 못했습니다.</p>}
      {deleteMutation.isLoading && <p>지우는 중입니다.</p>}
      {deleteMutation.isSuccess && <p>데이터가 성공적으로 지워졌습니다.</p>}
    </>
  );
profile
In the future, I'm never gonna regret, cuz I've been trying my best for every single moment.

0개의 댓글