useMutationState does not propagate generics into select callback (type inference lost) #9825
Send to my agentDescribe the bug#
The useMutationState hook doesn’t propagate generic type parameters (TData, TError, TVariables, TContext) into the select callback. As a result, when filtering by a specific mutationKey, TypeScript doesn’t infer correct types for mutation.state, forcing developers to cast manually.
Your minimal, reproducible example#
Steps to reproduce#
import { useMutationState } from '@tanstack/react-query'
type MyData = { data: string[] }
type MyError = { code: number; message: string }
type MyVars = { id: number }
const result = useMutationState<
MutationState<MyData, MyError, MyVars>
>({
filters: { mutationKey: ['KEY'] },
select: ({ state }) => state,
})
// Type '({ state }: Mutation<unknown, Error, unknown, unknown>) => MutationState<unknown, Error, unknown, unknown>' is not assignable to type '(mutation: Mutation<unknown, Error, unknown, unknown>) => MutationState<{ data: string[]; }, { code: number; message: string; }, { id: number; }, unknown>'.
Expected behavior#
When using filters.mutationKey to target a known mutation, the generic arguments should be propagated to the select callback:
select: (mutation: Mutation<MyData, MyError, MyVars>) => mutation.state
Current workaround - explicitly casting inside select:
select: (mutation) =>
mutation.state as MutationState<MyData, MyError, MyVars>
How often does this bug happen?#
None
Screenshots or Videos#
No response
Platform#
All
Tanstack Query adapter#
react-query
TanStack Query version#
v5.59.15
TypeScript version#
v5.9.3
Additional context#
No response
TkDodo added labelstypes
best I could come up with is this, but still needs a type assertion:
I also stumbled into this by following the v5 documentation for optimistic mutations https://tanstack.com/query/v5/docs/framework/react/reference/useMutationState:
import { useMutation, useMutationState } from '@tanstack/react-query' const mutationKey = ['posts'] // Some mutation that we want to get the state for const mutation = useMutation({ mutationKey, mutationFn: (newPost) => { return axios.post('/posts', newPost) }, }) const data = useMutationState({ // this mutation key needs to match the mutation key of the given mutation (see above) filters: { mutationKey }, select: (mutation) => mutation.state.data, })In my case the code looks more like this:
const queryKey = 'preferences' as const; const mutationKey = 'update-preference' as const; export const useUpdatePreferences = () => { const updatePreferences = usePatchPreferences(); const client = useQueryClient(); const mutation = useMutation({ mutationFn: updatePreferences, onSettled: () => client.invalidateQueries({ queryKey: [queryKey] }), mutationKey: [mutationKey], }); const variables = useMutationState({ filters: { mutationKey: [mutationKey], status: 'pending', }, select: (m) => m.state.variables as UpdatePreference, }); return { ...mutation, variables }; };where I override variables so that the user can change multiple preferences simultaneously.
Altering your example a bit @TkDodo, would it be possible to do something like this:
import { Mutation, MutationState, MutationFilters, QueryClient } from '@tanstack/react-query' declare function useMutationState<TResult = MutationState, TSelect = Mutation>(options?: MutationStateOptions<TResult, TSelect>, queryClient?: QueryClient): Array<TResult>; type MutationStateOptions<TResult = MutationState, TSelect = Mutation> = { filters?: MutationFilters; select?: (mutation: TSelect) => TResult | undefined; }; const result = useMutationState<string, Mutation<unknown, Error, string>>({ filters: { mutationKey: ['KEY'] }, select: (m) => m.state.variables, });I am unsure of the 'TResult | undefined' - that comes from TData and TVariables being typed with '| undefined' in the MutationState interface, but the result is still NonNullable. Its a small lie, but I think its always been there, though implicit.
Anyways, the type assertion isn't the end of the world, and I think using variables is a pretty neat way of achieving optimistic updates. If you find the time, let me know what you think. Keep up the good work.
TkDodo closed this
Sign in to join this conversation.
filters.mutationKeyallows for fuzzy matching, so by passing in['KEY'], you could potentially get multiple, matching queries at runtime.Also the type parameter we pass to
UseMutationStateis for theResulttype, not theMutationStateitself. we would have to add more type parameters touseMutationState, and sinceResultis the first type param, it means you would have to always define it, which isn’t nice.What are you trying to achieve with
useMutationStateexactly?