Mutation은 데이터를 읽는게 아닌 변경하는 로직에 대한 내용이다.
CREATEUPDATE,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>}
</>
);