Haaxor1689
Haaxor1689โ€ข2y ago

setMutationDefaults for optimistic updates

I have a preferences router, with a get query and a 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 endpoint, I don't want to copy paste the onSuccess for optimistic updates. There is the 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 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.
3 Replies
Haaxor1689
Haaxor1689OPโ€ข2y ago
Hmm I found this closed issue https://github.com/trpc/trpc/pull/3528 I guess the adding of mutationKey was forgotten about?
GitHub
expose getQueryKey on mutation procedures by hdwatts ยท Pull Request...
๐ŸŽฏ Changes In #3302 getQueryKey was exposed for all query procedures. I was hoping to be able to use the feature for setMutationDefaults - however the method was not exposed on mutation queries. Hap...
Haaxor1689
Haaxor1689OPโ€ข2y ago
After some investigation, turns out that for whatever reason, onSettled and onMutate work just fine. onSettled works only if I directly put it into hook call itself. oh I found the culprit
Haaxor1689
Haaxor1689OPโ€ข2y ago
Ok, made a PR with proposed fix ๐Ÿ™‚ https://github.com/trpc/trpc/pull/4371
GitHub
Fix some query and mutation defaults being overwritten in hook wrap...
Closes # ๐ŸŽฏ Changes Wrapper around useMutation hook was not honoring options set by getMutationDefaults hook at all. Default options are now loaded as well and used as a fallback to wherever opts ar...