T
TanStack2w ago
provincial-silver

Docs: Optimistic Updates issue

Hi everyone! I have an issue with optimistic docs example. In docs it says the following:
To do this, useMutation's onMutate handler option allows you to return a value that will later be passed to both onError and onSettled handlers as the last argument. In most cases, it is most useful to pass a rollback function.
To do this, useMutation's onMutate handler option allows you to return a value that will later be passed to both onError and onSettled handlers as the last argument. In most cases, it is most useful to pass a rollback function.
I read it as if I return data in onMutate function, onMutateResult will always be defined in onError | onSuccess | onSettled functions. And docs example suggests it also should work that way (first screenshot). But my result always can be undefined in every function (screenshot 2 and 3). Would appreciate any help and clarification on this issue, thanks!
No description
No description
No description
5 Replies
foreign-sapphire
foreign-sapphire2w ago
If you don't have strict mode enabled in your tsconfig, then you will never see null or undefined in the types. https://www.typescriptlang.org/tsconfig/#strict I would recommend double checking that you have this enabled as well as any other related strict flags set to true
TSConfig Reference - Docs on every TSConfig option
From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.
provincial-silver
provincial-silverOP2w ago
uuh, but why it can be undefined in a first place? I kinda dont want to disable strict mode. It should just infer a return type or a type that I just pass manually.
foreign-sapphire
foreign-sapphire2w ago
Ah I see what you meant, sorry for not understanding. Someone else will need to provide a definitive answer for why this is not always defined. My only real guess based on the source code that I can see is that query-core has that type, and so useMutation also has that type.
provincial-silver
provincial-silverOP2w ago
Yep. I need to figure out if there is some sort of underground logic that can return undefined or if is it just typed this way and for a short fix i can safely use onMutateResult!.previousData
foreign-sapphire
foreign-sapphire2w ago
https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L26 Line 178 is the execute function which looks to only call onSuccess when it has successfully made it past the onMutate call and has updated the mutation state with the updated context, so it would seem to me like it should be defined, but I haven't looked into it too much, just thought I would mention it since I had the file open when checking the types

Did you find this page helpful?