ajm
ajm

Reputation: 13213

Is it ok to call setQueryData from within onSuccess?

We have just migrated from react query v3 to react query v4. Official react query document to migrate mentions onSuccess is no longer called from setQueryData.

This is from the official documentation.

onSuccess is no longer called from setQueryData

This was confusing to many and also created infinite loops if setQueryData was called from within onSuccess. It was also a frequent source of error when combined with staleTime, because if data was read from the cache only, onSuccess was not called.

Similar to onError and onSettled, the onSuccess callback is now tied to a request being made. No request -> no callback.

If you want to listen to changes of the data field, you can best do this with a useEffect, where data is part of the dependency Array. Since React Query ensures stable data through structural sharing, the effect will not execute with every background refetch, but only if something within data has changed:

See below for more details.

https://tanstack.com/query/v4/docs/framework/react/guides/migrating-to-react-query-4#onsuccess-is-no-longer-called-from-setquerydata

There are few places in our app where we call setQueryData from onSuccess callback like below.

const useUpdateTitle = (id) => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (newTitle) =>
      axios
        .patch(`/posts/${id}`, { title: newTitle })
        .then((response) => response.data),
    onSuccess: (newPost) => {
      queryClient.setQueryData(['posts', id], newPost)
    },
  })
}

Such use cases are mostly while using useMutation hook and none while using useQuery hook.

From the above official documentation, I am not clear if this is while using useQuery or while using useMutation.

Is this ok or will this cause any problem?

Upvotes: 1

Views: 430

Answers (1)

Bhavesh Parvatkar
Bhavesh Parvatkar

Reputation: 2233

It's okay to use setQueryData from useMutation. Even official docs have examples on them.

Even with just variables, mutations aren't all that special, but when used with the onSuccess option, the Query Client's invalidateQueries method and the Query Client's setQueryData method, mutations become a very powerful tool.

The source for the above quote: https://tanstack.com/query/v4/docs/framework/react/guides/mutations

Examples:

Updating data: https://tanstack.com/query/v4/docs/framework/react/guides/updates-from-mutation-responses

Invalidating data: https://tanstack.com/query/v4/docs/framework/react/guides/invalidations-from-mutations

Upvotes: 1

Related Questions