react-query v4 공식문서 : Updates from Mutation Responses

👾·2022년 8월 12일
0

react-query

목록 보기
21/27
post-thumbnail

공식문서 : https://tanstack.com/query/v4/docs/guides/updates-from-mutation-responses

Updates from Mutation Responses

서버의 객체를 업데이트하는 mutation을 처리할 때, mutation의 response로 새로운 객체가 자동으로 반환되는것이 일반적이다. 해당 항목에 대한 쿼리를 refetch하고 이미 가지고 있는 데이터에 대한 네트워크 호출을 낭비하는 대신, mutation 함수에 의해 반환된 객체를 활용하고 Query Client의 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 로직을 재사용가능한 mutation에 연결하고 싶을 수 있다. 이를 위해 다음과 같은 커스텀 훅을 만들 수 있다. :

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)
    },
  })
}

0개의 댓글