const { data, isLoading, mutate, mutateAsync } = useMutation(mutationFn, options);
첫번째 인자에는 업데이트 될때 반응 할 비동기함수가 들어가며
두번째 인자에는 옵션이 들어간다.
useMutation에서 가장 많이 쓰는 3가지 옵션이 있습니다.
1. optimistic update
2. invalidateQueries
3. setQueryData
const updateMutation = useMutation(() => updatePost(post.id),{
onSuccess: () => { // 요청이 성공한 경우
console.log('onSuccess');
queryClient.invalidateQueries('getCommnet'); // queryKey 유효성 제거
},
});
useMutation의 설정 (공식문서)
// useMutation
const {
data,
error,
isError,
isIdle,
isLoading,
isPaused,
isSuccess,
mutate,
mutateAsync,
reset,
status,
} = useMutation(mutationFn, {
cacheTime,
mutationKey,
networkMode,
onError, // onError는 에러가 발생될 경우 실행되는 구간입니다.
onMutate,
onSettled, // onSettled는 finally 구문처럼 요청이 성공하든 에러가 발생되든 상관없이 마지막에 실행되는 구간입니다.
onSuccess, // onSuccess는 요청이 성공되었을 때 실행되는 구간입니다.
retry,
retryDelay,
useErrorBoundary,
meta
})
// mutate함수
mutate(variables, {
onError,
onSettled,
onSuccess,
})
const deleteMutation = useMutation((postId) => deletePost(postId));
<button
onClick={() => {
deleteMutation.mutate(post.id);
}}
>
밑에 예시를 보고 어떤건지 살펴보자
import { useMutation, useQuery } from "@tanstack/react-query";
async function fetchComments(postId) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/comments?postId=${postId}`
);
return response.json();
}
async function deletePost(postId) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/postId/${postId}`,
{ method: "DELETE" }
);
return response.json();
}
async function updatePost(postId) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/postId/${postId}`,
{ method: "PATCH", data: { title: "REACT QUERY FOREVER!!!!" } }
);
return response.json();
}
export function PostDetail({ post }) {
// replace with useQuery
const { data, isLoading, isError } = useQuery(["getCommnet", post.id], () =>
fetchComments(post.id)
);
const deleteMutation = useMutation((postId) => deletePost(postId)); //인수전달가능
const updateMutation = useMutation(() => updatePost(post.id));
if (isError) {
return "An error occurred";
}
return (
<>
{updateMutation.isLoading ? <p>updating data</p> : ""}
{updateMutation.isSuccess ? <p>update finish!</p> : ""}
{updateMutation.isError ? <p>updateError data</p> : ""}
<h3 style={{ color: "blue" }}>{post.title}</h3>
<button
onClick={() => {
deleteMutation.mutate(post.id);
}}
>
Delete
</button>
{deleteMutation.isError && <p>Error deleting the post</p>}
{deleteMutation.isLoading && <p>deleting the post</p>}
{deleteMutation.isSuccess && <p>Post has been deleted</p>}
<button onClick={() => updateMutation.mutate(post.id)}>
Update title
</button>
<p>{post.body}</p>
<h4>Comments</h4>
{isLoading ? (
<div>로딩중입니다...</div>
) : (
data?.map((comment) => (
<li key={comment.id}>
{comment.email}: {comment.body}
</li>
))
)}
</>
);
}