7. Mutations - 응답 업데이트

데이터를 업데이트하는 뮤테이션을 처리할 때 뮤테이션의 응답으로 새롭게 갱신된 데이터가 반환되는 것이 일반적 입니다.

이 때, 새롭게 갱신된 데이터를 가져오기 위해 다시 쿼리하는 것은 네트워크 호출을 낭비하는 것 이므로 뮤테이션에서 반환된 객체를 활용해서 쿼리 클라이언트의 setQueryData 메서드를 사용해서 즉시 갱신된 데이터로 기존 쿼리를 업데이트 할 수 있습니다.

const queryClient = useQueryClient();
 
 const mutation = useMutation(editTodo, {
   onSuccess: data => {
     queryClient.setQueryData(['todo', { id: 5 }], data)
   };
 });
 
 mutation.mutate({
   id: 5,
   name: 'Do the laundry',
 });
 
 // The query below will be updated with the response from the
 // successful mutation
 const { status, data, error } = useQuery(['todo', { id: 5 }], fetchTodoById);

커스텀 훅을 사용해서 onSuccess 를 추상화 할 수 있습니다.

const useMutateTodo = () => {
   const queryClient = useQueryClient()
 
   return useMutation(editTodo, {
     // Notice the second argument is the variables object that the `mutate` function receives
     onSuccess: (data, variables) => {
       queryClient.setQueryData(['todo', { id: variables.id }], data)
     },
   })
 }

Last updated