728x90
반응형
useMutation 이란?
React-Query를 이용해 서버에 변경(insert, update,delete)작업 요청시 사용
const { mutate, isLoading } = useMutation({
mutationFn: async (newDriveData) => {
const response = await axiosInstance.post("/api/drive/newDrive", newDriveData);
return response.data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['driveList', user.uid] });
onClose();
},
onError: (error) => {
console.error("Error creating drive:", error);
},
});
const handleSubmit = () => {
console.log("최종 제출 ",formData);
mutate(formData);
};
Options
mutationFn (variables: TVariables) => Promise<TData> (필수)
- Required
- 비동기 작업을 수행하고 프로미스를 반환하는 함수이다. (쉽게 말해 api 요청하는 함수)
- variables 는 mutate가 전달하는 객체이다.
onMutate: (variables: TVariables) => Promise<TContext | void> | TContext | void (선택사항)
- onMutate 는 mutation 함수가 실행되기 전에 실행되고 mutation 함수가 받을 동일한 변수가 전달된다.
- optimistic update 사용 시 유용한 함수이다.
onSuccess: (data: TData, variables: TVariables, context?: TContext) => Promise<unknown> | voi
- onSuccess 는 mutation 이 성공하고 결과를 전달할 때 실행된다.
onError: (err: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void
- onError 는 mutation 이 error 를 만났을 때 실행된다. 오류가 발견되었을때, 실행되고 오류가 전달됨
onSettled: (data: TData, error: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void
- onSettled 는 mutation 이 성공해서 성공한 데이터 또는 error가 전달될 때 실행된다. (성공하든 실패하든 아무튼 결과가 전달된다)
Return s
mutate: (variables: TVariables, { onSuccess, onSettled, onError }) => void
- mutate 를 호출해서 mutation 을 실행시킬 수 있다.
- variables 는 mutationFn 에 전달하는 객체이다.
- onSuccess, onSettled, onError 는 useMutation option에 설명한 것과 동일하다.
- 변수와 함께 호출하여 돌연변이를 트리거할 수 있는 함수이며, 선택적으로 추가 콝백 옵션에 연결할 수 있음.
- mutationFn에 전달할 변수 객체를 받아서 보낸다.
queryClient 쿼리 클라이언트
=> 사용자 정의 쿼리 클라이언트를 호출하여 UI상에 변경된 내뇽을 적용시킴
728x90
반응형
댓글