TanStackT
TanStack11mo ago
9 replies
urgent-maroon

setQueryData inside mutation behavior

I copied following example from the course:

function useUpdateUser() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: updateUser,
    onSuccess: (newUser) => {
      queryClient.setQueryData(['user', newUser.id], newUser)
    }
  })
}

What happens if the
isPending
of this mutation is being used to show or hide specific components on a page. For example a component showing the user details in a form, using as initial values those provided by
useQuery
matching the key of the mutation above.

queryClient.setQueryData is being called in the
onSuccess
which I think means that while calling queryClient.setQueryData,
isPending
inside the component using the mutation is actually
false
, is that correct?

I think I saw an issue locally where my form (Mantine use-form) was using outdated initial values due to queryClient.setQueryData still being 'in progress'. Is this something someone else also experienced, if so, how should I work around this?

I assume the data from
useQuery
is updated in a later render cycle, pushing the new props to the form component but they are not taking into account as the form already rendered.
Was this page helpful?