`mutate` doesn't update `variables` synchronously #9062
Send to my agentDescribe the bug#
Hello! I looked for an existing issue and couldn't find so opening here.
I noticed a problem when trying to use myMutation.variables as the value prop in a textarea. My hope was that I could do that as a way to avoid synchronizing with a useState while using the mutation to send updates to the server. More or less this:
export function MyComponent() {
const myMutation = useMutation({
mutationFn: async (params: {text: string}) => {
await new Promise(r => setTimeout(r, 500))
return params.text.split(',')
},
})
return <textarea
value={myMutation.variables?.text || ''}
onChange={ev => myMutation.mutate({text: ev.target.value})}
/>
}
This mostly works, but if you try to edit something at the beginning of the textarea, the cursor jumps to the end.
According to this blog this happens when the value prop is updated asynchronously: https://dev.to/kwirke/solving-caret-jumping-in-react-inputs-36ic
I made a demo, along with a workaround which wraps the mutation and uses useState to store a synchronous copy of variables: - on the left, the cursor "jumps" to the end when you type at the start of the textarea.
Your minimal, reproducible example#
https://v0.dev/chat/react-query-demo-ec5BxFS85Rs?f=1
Steps to reproduce#
- Go to the link above
- Type stuff in both boxes
- Move the cursor to the start and keep typing. It jumps to the end on the left, but not on the right
Expected behavior#
I'd expect the cursor not to jump around.
The following helper can wrap a mutation at make it work that way:
function useMutationWithLocalVariables<Mutation extends { mutate: (args: any) => void; variables: any }>(
mutation: Mutation,
): Mutation {
const { variables: _v, mutate: _m, ...rest } = mutation
const [variables, setVariables] = useState<typeof _v>()
const mutate = useCallback<typeof _m>(
mutateArgs => {
setVariables(mutateArgs)
return void _m(mutateArgs)
},
[_m, setVariables],
)
return { ...rest, mutate, variables } as Mutation
}
Usage
const myMutation = useMutationWithLocalVariables(useMutation(...))
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- any platform
Tanstack Query adapter#
None
TanStack Query version#
5.74.3
TypeScript version#
5
Additional context#
No response
Well it is possible to get the desired behaviour with the wrapper
useMutationWithLocalVariablesabove - so it's not like there's some fundamental restriction in react. As far as I understand (having googled this problem... yesterday) react will make the cursor jump around if the update for the textarea/input/whatevervalueis synchronous, e.g. howuseStateworks.Looking at the code, it's likely because:
.mutate(...)callsobserver.mutate(variables, mutateOptions).catch(noop)(MutationObserver::mutate), which returns a Promise and is async:So maybe, in theory, if react-query avoided
asyncuntil the variables were updated synchronously, this would work. I tried playing around in node_modules and couldn't quite get it to do that/figure out how exactly the react state system is being used, so maybe that's a non-trivial request.Is there another recommended way to achieve what I want here? That is, to have every
onChangeto a textarea/input to triggermyMutation.mutate({text: ev.target.value})and keepvariablesin sync with some synchronous state value. A wrapper like above? Or auseState/useEffect?const MyComponent = () => { const myMutation = useMutation({ mutationFn: async (params: {text: string}) => {/**/}, }) const [text, setText] = useState<string>() useEffect(() => { if (typeof text === 'string') mutationFn.mutate({text}) }, [text]) return <textarea value={text || ''} onChange={ev => setText(ev.target.value)} /> }The above is fine I guess too, but usually I like react-query because it is keeping track of all this state for me. Adding in a useState and useEffect feels wrong.
There are updates to the mutation state (calls to
this.#dispatch) that definitely have to happen in an async context, and it might be those that are causing those destructive re renders, not the first dispatch before the await calls start. I can play a bit with makingexecutenon-async and have it return a promise from an inner async call but I'm sorta stumped myself otherwise wise (maybe React Compiler fixes this?)Everything is
asyncin react query. Even if we madeexecutesynchronous (which is weird to begin with, as you’d maybe like toawait mutateAsyncand then you can’t do it), I don’t think it would solve the problem. We synchronusly calldispatchto setvariablesinto our state:and that synchronously sets state in our external store, but the mechanism to inform observer about that is batched by us and potentially batched by react, too.
Is there another recommended way to achieve what I want here? That is, to have every onChange to a textarea/input to trigger myMutation.mutate({text: ev.target.value}) and keep variables in sync with some synchronous state value.
Just don’t use variables for rendering? Create a “normal” controlled component with react state and fire the mutation in the event handler:
const [text, setText] = useState('') return <textarea value={text} onChange={ev => { setText(ev.target.value) mutate(ev.target.value) }} />TkDodo closed this
TkDodo added labelshas workaround
TkDodo added labelsknown limitation
Sign in to join this conversation.
I think this is how react works. Not sure what we could do about it ?