You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Status of useMutation not shared across usages/components with custom hook (like useQuery does) #2304
Imagine creating a custom hook (let's name it useTodos) which is used in multiple components and uses useQuery and useMutation inside.
When using useQuery, its status (and the helpers isLoading, isError, ...) are shared across multiple usages of useTodos.
For useMutation, this is not true. Every usage of useTodos will have its own mutation status.
It shows two components that both use useTodos.
For GET requests (via useQuery), the status is shared across the components.
For POST requests (via useMutation), the status is different for both components. Only the component who executes the mutation will have the status "error".
Expected behavior
I understand that useQuery has one precise query key to identify "the same hook". Mutations are not like that.
In my case, I had a list that showed items (like "Todos") and a child component that was supposed to create a new item (like "Todo"). Naturally, I used useTodos in both components and wanted to show an error in the List component. The problem is isError was never true, only the child component's one was.
functionTodoList(){// this "isError" here will never be true, only the <Todo> component's "isError" willconst{ todos, isError }=useTodos();return(<div><p>Todos:</p>{isError&&<p>Error!</p>}<div>{todos.map((todo)=>(<Todotodo={todo}/>))}</div></div>);}functionTodo({ todo }: {todo: Todo|null}){const{ createTodo }=useTodos();return(<div>{todo ? (<p>{todo.title}</p>) : (<div><buttononClick={()=>createTodo(...)}>Create</button><input.../>
...
</div>
)}</div>);}
I'm using React Query for a while now and being used to useQuery having a shared status, I wasted time checking my mutation implementation ("Why is the error not thrown?" etc.), but in reality useQuery and useMutation just behave differently and differently than expected.
I would really like to let useMutations share their status across all components.
There's already a mutationKey, which could maybe used for this exact use case.
Reacted by Mihail-Florin Popa, Jan Moravec, Vlad Klimov, orouz, Alexis Mangin, Eugene, Juan Riquelme, Sergey Sergeyev, Jim, Juan Cruz Rabaglia and 82 more
Reacted by Pedro H. Santiago, Antogin, Yony and Pradeep G
Yes, I was also surprised by this, but mutationKey is not required, unlike the queryKey, so we can't really create a subscription like for useQuery. Mutations are also imperative so it just doesn't happen very often I guess. What we do have is the useIsMutating hook, similar to the useIsFetching hook, so that you know when a mutation is in-flight, and you can filter these by mutationKey. With that, you can e.g. disable all buttons that would trigger the same mutation. Not sure how that would fix the error situation though - but you can take a look how to create a subscription to the mutationCache by looking at the impl of useIsMutating:
Reacted by inf1nite-lo0p, strarsis, Steven Broderick, anggonoou, James Chung, Changdae Park, Giovanni, TienNguyen, David Tello, Szigeti Péter and 8 more
@TkDodo Thanks for the feedback and possible workaround.
I could also create my own React context and save isError or isLoading there, so all components have the same status - I just thought it'd be nice to let React Query provide this out of the box.
Feel free to move this issue to the discussions, so we keep it there as a "feature request".
Feel free to move this issue to the discussions, so we keep it there as a "feature request".
let's keep here, I'd like to analyze how hard it would be to actually use the mutationKey to achieve that functionality, or if that would be a breaking change.
Reacted by Bennett Dams, Prateek Surana, Sixian Li, Sylvain Boulade, Changdae Park, SimonGodefroid, David Tello and Victor K Varghese
I always attach mutationKey and then got to the part where i needed to share if it ever succeeded or failed count and same thing. Thanks for bringing up this topic, it was first hit on search engine. I should have searched first rather then assume.
I was very surprised to find this out today when my mutation hook wasn't working as expected. I've also run into issues like the one described here as well as #2294. Losing transient mutation state like isLoading or error when your component changes contexts is unfortunate.
It made me start to wonder why there's such a strong conceptual distinction between queries and mutations, when at the end of the day they're both just abstractions around some promise that returns data, generally an HTTP request.
You could almost use useQuery in place of useMutation today if it exposed the imperative functions like mutate and mutateAsync and if it had a callback like onMutate. The key difference between the two hooks seems to come down to configuration, e.g. queries execute on lifecycle events by default, mutations do not retry by default, etc. I could imagine both of these hooks being thin wrappers around some other hook that provides all the common functionality, such as useRequest. This could even simplify some of the internals for RQ - one cache instead of separate query and mutation cache.
I could easily be overlooking some important details or underestimating the complexity, but I do agree that the state behavior of useMutation is not intuitive and inconsistent with useQuery.
Reacted by Pietro Paolo Vismara, tlareg, David Cheng, Changdae Park, Abdulhamit Akaslan, Juliano, Marc Schmidt, puneetmakkar, André Crimberg, Alexander Komarov and 1 more
@stefan-toubia it is something that is on my mind for quite some time. What if mutations were conceptually "just" disabled queries, where mutate or mutateAsync just calls refetch() 🤔 .
Not only would that get rid of a ton of internal code (MutationCache, Mutation, MutationObserver, ...), it would also, at the same time, add a lot of features for mutations, like sharing data, select and other options.
Of course, we could still turn off some of the options and / or set different default values for useMutation.
However, when I went down that road, there is one thing that works inherently different from queries:
useQuery instantly creates an observer, but useMutation only does it after .mutate is called. Further, if you call .mutate multiple times, the previous observer is unsubscribed automatically. That is necessary so that callbacks of .mutate are only called once. However, callbacks on useMutation itself are actually cache level callbacks, which will execute any time the mutation succeeds / fails, even if the observer has already unmounted. That is important, and something that doesn't exist on the query cache itself.
Feel free to take a look at the implementation (best on v4 directly, alpha branch), the road would need to be a merging of the two slightly different functionalities. Would love to have it but I don't have enough time to look into it right now :)
Reacted by Andreas Herd, Lucas Inacio, Changdae Park, Abdulhamit Akaslan, puneetmakkar, Yaroslav Bukhta and Edgar Ortega
Reacted by Kalle, Lucas Inacio, Changdae Park, puneetmakkar, Eden Turgeman and Edgar Ortega
Just thought to provide code for another workaround for this issue, which doesn't require manually keeping state but still allows different components to share the same mutation object. As mentioned, just wrap a react context around the custom hook and the desired functionality will be achieved. https://codesandbox.io/s/silent-frost-mjxlrf?file=/src/App.js
constCustomMutationProvider=({ children })=>{constmutation=useMutation({mutationKey: "UpdateData",mutationFn: async()=>{// Fake api callawaitnewPromise((resolve,reject)=>setTimeout(reject,2000));}});return(<CustomMutationContext.Providervalue={mutation}>{children}</CustomMutationContext.Provider>);};constCustomMutationContext=React.createContext();constuseCustomMutation=()=>React.useContext(CustomMutationContext);
And use like so:
constqueryClient=newQueryClient();exportdefaultfunctionApp(){return(<divclassName="App"><QueryClientProviderclient={queryClient}><CustomMutationProvider><ComponentA/><ComponentB/></CustomMutationProvider></QueryClientProvider></div>);}constComponentA=()=>{const{ mutate, status }=useCustomMutation();return(<div><h1>Component A </h1>
Status: {status}<br/><buttononClick={mutate}>Update</button></div>);};constComponentB=()=>{const{ mutate, status }=useCustomMutation();return(<div><h1>Component B </h1>
Status: {status}<br/><buttononClick={mutate}>Update</button></div>);};
Reacted by Kalle, Stefan Toubia, Yashvi Mehta, Dominik Dorfmeister 🔮, Nick Foscarini, MarcinKapiszewski, puneetmakkar, Robert Frost, Tan Ahmed and Peter
Reacted by Robert Frost and Eden Turgeman
Reacted by Sebastián Urbano, Antoniel Magalhães, Leonardo Tuna, H.Abderrahmane, Marc Schmidt, André Crimberg, Daniel Infante, Dan Pankratev, Ivan Ihnatsiuk, Yaroslav Bukhta and 4 more
If I understood the reason correctly, the following worked for me:
// workaround for https://github.com/TanStack/query/issues/2304// instead of useIsMutatingconst[isMutating,setIsMutating]=useState(false);useEffect(()=>{returnqueryClient.getMutationCache().subscribe(({ type, mutation })=>{if(type==='updated'&&mutation.options.mutationKey?.[0]==='KEY'// your predicate here){setIsMutating(mutation.state.status==='loading');}});},[]);
Reacted by puneetmakkar, Nurbek, Eden Turgeman and Maria Kondaurova
Reacted by heedoWang, vunguyen464301, Eden Turgeman, Sadegh Barati and Dương Đình Thiện Vũ
function useShippingZone() {
const address = useAppSelector(selectAddress);
const queryKey = ["getShippingZone", address.zipCode];
const result = useQuery(queryKey, getShippingZone, {
meta: address as IndexSignature<typeof address>,
});
}
async function getShippingZone({ meta }: QueryFunctionContext<...>) {
const address = meta as unknown as Address;
...
}
type IndexSignature<O extends object> = {
[P in keyof O]: O[P] extends object ? IndexSignature<O[P]> : O[P];
};
where you need to pass variables through meta option. (which is very vulnerable in typing, and not really recommended as other developers wouldn't think that's what meta should be used for). But for this case where I anyway save address in a global state, I think it's worth to do.
Based on @TkDodo answers #2304 (comment), I've implemented my useCustomMutation that uses useQuery to share data between components.
My first use-case that requires that useMutation share data across components was a multi-step form in react-native (ps: in react-native, the stack navigation doesn't unmount the previous screen) where at the first page, we need to get an AuthToken, we do it onPress of a button by the user, so it makes sense to be a mutation at this point, but I faced that if I need to get the token on subsequent screens, it will not be there, so that's why of the implementation.
The useCustomMutation follows the exactly same API of useMutation
exportconstuseCustomMutation=<TData=unknown,TError=unknown,TVariables=unknown,TContext=unknown>(mutationKey: MutationKey,mutationFn: MutationFunction<TData,TVariables>,options?: Omit<UseMutationOptions<TData,TError,TVariables,TContext>,'mutationKey'|'mutationFn'>): UseMutationResult<TData,TError,TVariables,TContext>=>{constquery=useQuery<TData,TError>(['CustomMutation',mutationKey],async()=>awaitPromise.resolve(falseasunknownasTData),{retry: false,cacheTime: Infinity,staleTime: Infinity})constqueryError=useQuery<TError,TData>(['CustomMutationError',mutationKey],async()=>awaitPromise.resolve(falseasunknownasTError),{retry: false,cacheTime: Infinity,staleTime: Infinity})constmutation=useMutation<TData,TError,TVariables,TContext>(mutationKey,async(...params)=>{queryClient.setQueryData(['CustomMutationError',mutationKey],false)returnawaitmutationFn(...params)},{
...options,onSuccess: (data,variables,context)=>{queryClient.setQueryData(['CustomMutation',mutationKey],data)if(options?.onSuccess)options.onSuccess(data,variables,context)},onError: (err,variables,context)=>{queryClient.setQueryData(['CustomMutationError',mutationKey],err)if(options?.onError)options.onError(err,variables,context)},})constisLoading=useIsMutating(mutationKey)// We need typecasting here due the ADT about the mutation result, and as we're using a data not related to the mutation result// The typescript can't infer the type correctly.// eslint-disable-next-line @typescript-eslint/consistent-type-assertionsreturn{
...mutation,data: query.data,isLoading: !!isLoading,error: queryError.data,isError: !!queryError.data,}asUseMutationResult<TData,TError,TVariables,TContext>}
Reacted by Guilherme dos Reis Meira, Miguel Gomes, José Ferreira, Guillermo Maiolo, Vinicius Vicentini, Kalle, Changdae Park, Szabolcs Kelemen, Abdulhamit Akaslan, Prashant and 5 more
Reacted by Miguel Gomes, José Ferreira, Kalle, Jorge Habib El Khouri, Yony and Eden Turgeman
Reacted by H.Abderrahmane, Kalle, Shahar Yakir, Jorge Habib El Khouri and Sergey Lebedev
TGhanks @antoniel for sharing, I think that onSuccess etc will only fire if the component remains mounted. I think you'll have to move the success/error into the queryFn.
Well, yes. There will likely be something in v5, but it will not mean that useMutation will share state, because every invocation of useMutation.mutate creates a new, completely separate mutation entry. It's fundamentally different from useQuery.
Instead, we will likely have a new hook useMutationState() where you can pass in filters and potentially a selector. It's like useIsMutating (which in fact is now implemented with useMutationState) but for arbitrary fields of the mutation, like data or error or something derived. It will always return an array, because unlike queries, there can be multiples even for the exact same mutationKey by just calling mutate twice on the same "instance".
changes are somewhere in this PR if you're interested:
@Chunkford I don't think your problem has anything to do with this issue. Please just open a separate discussion (discussion, not issue 😉)
Reacted by Kalle, puneetmakkar, Antoniel Magalhães, Alexander Popoff, orcharddweller, Jonathan Jay Mayol, Philip Feldmann, Eranda Kudalugodaarachchi, nishan (o^▽^o), Ricardo Sousa and 4 more
Reacted by Bennett Dams, zilahir, Dmitrii Bykov, OneTube, junglast, Juan Morales (Milo), André Vendramini, Tom Larkworthy, Alexander Komarov, Naufal Abbad and 7 more
Activity
TkDodo commentedon May 21, 2021
Yes, I was also surprised by this, but
mutationKeyis not required, unlike thequeryKey, so we can't really create a subscription like foruseQuery. Mutations are also imperative so it just doesn't happen very often I guess. What we do have is theuseIsMutatinghook, similar to theuseIsFetchinghook, so that you know when a mutation is in-flight, and you can filter these by mutationKey. With that, you can e.g. disable all buttons that would trigger the same mutation. Not sure how that would fix the error situation though - but you can take a look how to create a subscription to the mutationCache by looking at the impl ofuseIsMutating:https://github.com/tannerlinsley/react-query/blob/master/src/react/useIsMutating.ts
bennettdams commentedon May 25, 2021
@TkDodo Thanks for the feedback and possible workaround.
I could also create my own React context and save
isErrororisLoadingthere, so all components have the same status - I just thought it'd be nice to let React Query provide this out of the box.Feel free to move this issue to the discussions, so we keep it there as a "feature request".
VolodymyrBaydalka commentedon May 25, 2021
I have similar "Idea" under the discussions section - #2294
TkDodo commentedon May 25, 2021
let's keep here, I'd like to analyze how hard it would be to actually use the
mutationKeyto achieve that functionality, or if that would be a breaking change.Noitidart commentedon Oct 5, 2021
I always attach mutationKey and then got to the part where i needed to share if it ever succeeded or failed count and same thing. Thanks for bringing up this topic, it was first hit on search engine. I should have searched first rather then assume.
stefan-toubia commentedon Jan 13, 2022
I was very surprised to find this out today when my mutation hook wasn't working as expected. I've also run into issues like the one described here as well as #2294. Losing transient mutation state like
isLoadingorerrorwhen your component changes contexts is unfortunate.It made me start to wonder why there's such a strong conceptual distinction between queries and mutations, when at the end of the day they're both just abstractions around some promise that returns data, generally an HTTP request.
You could almost use
useQueryin place ofuseMutationtoday if it exposed the imperative functions likemutateandmutateAsyncand if it had a callback likeonMutate. The key difference between the two hooks seems to come down to configuration, e.g. queries execute on lifecycle events by default, mutations do not retry by default, etc. I could imagine both of these hooks being thin wrappers around some other hook that provides all the common functionality, such asuseRequest. This could even simplify some of the internals for RQ - one cache instead of separate query and mutation cache.I could easily be overlooking some important details or underestimating the complexity, but I do agree that the state behavior of
useMutationis not intuitive and inconsistent withuseQuery.TkDodo commentedon Jan 14, 2022
@stefan-toubia it is something that is on my mind for quite some time. What if mutations were conceptually "just" disabled queries, where
mutateormutateAsyncjust callsrefetch()🤔 .Not only would that get rid of a ton of internal code (MutationCache, Mutation, MutationObserver, ...), it would also, at the same time, add a lot of features for mutations, like sharing data,
selectand other options.Of course, we could still turn off some of the options and / or set different default values for
useMutation.However, when I went down that road, there is one thing that works inherently different from queries:
useQueryinstantly creates an observer, butuseMutationonly does it after.mutateis called. Further, if you call.mutatemultiple times, the previous observer is unsubscribed automatically. That is necessary so that callbacks of.mutateare only called once. However, callbacks onuseMutationitself are actually cache level callbacks, which will execute any time the mutation succeeds / fails, even if the observer has already unmounted. That is important, and something that doesn't exist on the query cache itself.Feel free to take a look at the implementation (best on v4 directly, alpha branch), the road would need to be a merging of the two slightly different functionalities. Would love to have it but I don't have enough time to look into it right now :)
nextrapi commentedon Jul 1, 2022
Just thought to provide code for another workaround for this issue, which doesn't require manually keeping state but still allows different components to share the same mutation object. As mentioned, just wrap a react context around the custom hook and the desired functionality will be achieved.
https://codesandbox.io/s/silent-frost-mjxlrf?file=/src/App.js
And use like so:
welcomemax commentedon Aug 3, 2022
If I understood the reason correctly, the following worked for me:
cdpark0530 commentedon Aug 15, 2022
I got into this today. My current workaround is
where you need to pass variables through
metaoption. (which is very vulnerable in typing, and not really recommended as other developers wouldn't think that's whatmetashould be used for). But for this case where I anyway saveaddressin a global state, I think it's worth to do.antoniel commentedon Sep 2, 2022
Based on @TkDodo answers #2304 (comment), I've implemented my useCustomMutation that uses useQuery to share data between components.
My first use-case that requires that useMutation share data across components was a multi-step form in react-native (ps: in react-native, the stack navigation doesn't unmount the previous screen) where at the first page, we need to get an AuthToken, we do it onPress of a button by the user, so it makes sense to be a mutation at this point, but I faced that if I need to get the token on subsequent screens, it will not be there, so that's why of the implementation.
The
useCustomMutationfollows the exactly same API ofuseMutationYou can find it also on a gist: https://gist.github.com/antoniel/1f8d59f7e3f73487e5ba02a293fb39ec
Noitidart commentedon Sep 2, 2022
TGhanks @antoniel for sharing, I think that
onSuccessetc will only fire if the component remains mounted. I think you'll have to move the success/error into thequeryFn.leotuna commentedon Oct 13, 2022
Any updates? Using the context API is solves the problem but it is still a bad solution.
SzabKel commentedon Oct 19, 2022
@antoniel 's solution worked for me as well. I used the
useQueryClienthook to get thequeryClient.JasoonX commentedon Jan 4, 2023
Are there any updates?
leotuna commentedon Feb 5, 2023
Any updates?
andrecrimb commentedon Feb 10, 2023
Updates ?
Chunkford commentedon Feb 12, 2023
TkDodo commentedon Feb 12, 2023
Well, yes. There will likely be something in v5, but it will not mean that
useMutationwill share state, because every invocation ofuseMutation.mutatecreates a new, completely separate mutation entry. It's fundamentally different fromuseQuery.Instead, we will likely have a new hook
useMutationState()where you can pass in filters and potentially a selector. It's likeuseIsMutating(which in fact is now implemented withuseMutationState) but for arbitrary fields of the mutation, likedataorerroror something derived. It will always return an array, because unlike queries, there can be multiples even for the exact same mutationKey by just callingmutatetwice on the same "instance".changes are somewhere in this PR if you're interested:
@Chunkford I don't think your problem has anything to do with this issue. Please just open a separate discussion (discussion, not issue 😉)
TkDodo commentedon Feb 20, 2023
v5 PR was merged
[dapp-kit] create new wallet provider for managing wallet connection …
[dapp-kit] create new wallet provider for managing wallet connection …