tRPCttRPC
Powered by
Haaxor1689H
tRPCโ€ข3y agoโ€ข
4 replies
Haaxor1689

setMutationDefaults for optimistic updates

I have a
preferences
preferences
router, with a
get
get
query and a
set
set
mutation. I had optimistic updates set up in the onSuccess of the useMutation hook, wherever I used it, like this:

const preferences = api.preferences.get.useQuery();
const savePreferences = api.preferences.set.useMutation({
  onSuccess: v =>
    queryClient.setQueryData(
      getQueryKey(api.preferences.get, undefined, 'query'),
      v
    )
});
const preferences = api.preferences.get.useQuery();
const savePreferences = api.preferences.set.useMutation({
  onSuccess: v =>
    queryClient.setQueryData(
      getQueryKey(api.preferences.get, undefined, 'query'),
      v
    )
});


Now that I'm adding more and more instances where I need to use the
set
set
endpoint, I don't want to copy paste the
onSuccess
onSuccess
for optimistic updates. There is the
setMutationDefaults
setMutationDefaults
function of query client that would be ideal for this but it isn't working.

queryClient.setMutationDefaults(getQueryKey(api.preferences.set), {
  onSuccess: v =>
    queryClient.setQueryData(
      getQueryKey(api.preferences.get, undefined, 'query'),
      v
    )
})
queryClient.setMutationDefaults(getQueryKey(api.preferences.set), {
  onSuccess: v =>
    queryClient.setQueryData(
      getQueryKey(api.preferences.get, undefined, 'query'),
      v
    )
})


Is this not working in tRPC wrapper because it's not setting the
mutationKey
mutationKey
or am I doing something wrong? Like I could make a wrapper hook for this mutation but using these defaults seems to me like much cleaner solution.
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

trpc optimistic updates causing data flicker
Liltripple_reidLLiltripple_reid / โ“-help
2y ago
optimistic updates tRPC v11 + TanStack Query v5
SparkSSpark / โ“-help
3y ago
Multiple optimistic updates and old data from refetches
cugsCcugs / โ“-help
3y ago