useMutation_ReactQuery

miin·2023년 11월 2일
0

React

목록 보기
49/52
post-thumbnail

POST, PUT, DELETE와 같은 변경 및 수정 작업을 할 때 사용되는 훅

const requestData = useMutation(API 호출 함수, 콜백);

 const loginMutation = useMutation(loginApi, {
    onMutate: variable => {
      console.log("onMutate", variable);
      // variable : {loginId: 'xxx', password; 'xxx'} 
    },
    onError: (error, variable, context) => {
      // error
    },
    onSuccess: (data, variables, context) => {
      console.log("success", data, variables, context);
    },
    onSettled: () => {
     //onSuccess와 같은 데이터 들어옴
    }
  });
  • 예시
  const { mutate: deleteAccountHandler } = useMutation(
    () => AxiosApi.delete(`/partner/${deleteAccountId}/partner-delete`),
    {
      onSuccess: (data) => {
        if (data.data.error_code !== 200) {
          alert(data.data.message)
          return
        }
        alert('계정이 삭제되었습니다.')
      },
      onError: (error) => {
        console.log({ error })
      },
    },
  )
import { useMutation } from "react-query";
// 더 많은 return 값들이 있다. 
const { data, isLoading, mutate, mutateAsync } = useMutation(mutationFn, options);

mutate(variables, {
onError,
onSettled,
onSuccess,
});

0개의 댓글