Skip to main content

React Query useMutation


useMutation

useMutation은 Create/Update/Delete 처럼 서버 상태를 변경하는 작업을 수행하는데 사용됩니다.

import { useMutation } from "@tanstack/react-query";

const mutation = useMutation({
mutationFn, // (variables: TVariables) => Promise<TData>
cacheTime,
mutationKey,
networkMode,
onError, // (err: TError, variables: TVariables, context?: TContext) => Promise<unknown> | unknown
onMutate, // (variables: TVariables) => Promise<TContext | void> | TContext | void
onSettled, // (data: TData, error: TError, variables: TVariables, context?: TContext) => Promise<unknown> | unknown
onSuccess, // (data: TData, variables: TVariables, context?: TContext) => Promise<unknown> | unknown
retry,
retryDelay,
useErrorBoundary,
meta,
});

const {
data,
error,
isError,
isIdle,
isLoading,
isPaused,
isSuccess,
failureCount,
failureReason,
mutate,
mutateAsync,
reset,
status,
} = mutation;

mutation.mutate(variables, {
localOnError, // (err: TError, variables: TVariables, context: TContext | undefined) => void
localOnSettled, // (data: TData | undefined, error: TError | null, variables: TVariables, context: TContext | undefined) => void
localOnSuccess, // (data: TData, variables: TVariables, context: TContext) => void
});
  • mutation.mutate를 호출하면 onMutate -> mutationFn -> ((onSuccess -> localOnSuccess) || (onError -> localOnError)) -> onSettled -> localOnSettled 순으로 실행됩니다.