query icon indicating copy to clipboard operation
query copied to clipboard

onSuccess callback in useQuery fires twice

Open sshmyg opened this issue 5 years ago • 24 comments

Describe the bug useQuery call one by one for same endpoint but for different components (one component should be child for other and parent should render child only on isLoading === false);

To Reproduce Steps to reproduce the behavior (visit link for details): https://codesandbox.io/s/vigilant-swartz-ox5p9?file=/src/App.js

Expected behavior onSuccess should be called once.

Screenshots First load image

Desktop (please complete the following information):

  • OS: mac os 11.1
  • Browser: chrome
  • Version: 89.0.4389.82

sshmyg avatar Mar 15 '21 10:03 sshmyg

this is very likely because both components are using the same queryKey (repoData). each observer is informed when new data is fetched, so I think it goes as follows:

  • component 1 mounts, data is fetched, onSuccess is called, data is immediately stale.
  • now component 2 mounts (conditionally, because component 1 is no longer loading). this triggers a background refetch, because data is stale.
  • when the background refetch finishes, both observers of the key repoData are informed, and onSuccess is triggered for both of them.

to mitigate this, you can:

  • ~~create a custom hook with only one onSuccess callback~~
  • render both observers at the same time, not conditionally one after the other
  • set a small staleTime to avoid immediate background updates
  • ~~use unique query keys~~

TkDodo avatar Mar 15 '21 10:03 TkDodo

@TkDodo Thanks for the response. But don't you think onSuccess callback should be uniq and doesn't depend on queryKey ? I found workaround, but it looks pretty much like a bug. What if I want to have a single cache for different calls but I need separate onSuccess?

sshmyg avatar Mar 15 '21 10:03 sshmyg

sorry, my bullet list above might not be totally correct. callbacks are unique per observer (=useQuey call), which is why you see them both being executed. if you have the same queryKey, like you do above, and two observers where both have an onSuccess callback, both will be called.

Is this now the behaviour you expect or not?

I updated my comment above. if you render both observers at the same time, react-query will dedupe the request and only call each callback once. if you set a small staleTime, mounting the second observer will not result in a background fetch, and thus the second onSuccess will not be called at all (because there is no request).

I think I need to understand what problem you are trying to solve here 🤷

TkDodo avatar Mar 15 '21 10:03 TkDodo

sorry, my bullet list above might not be totally correct. callbacks are unique per observer (=useQuey call), which is why you see them both being executed. if you have the same queryKey, like you do above, and two observers where both have an onSuccess callback, both will be called.

No, I would like to have uniq onSuccess not depends on queryKey. But have an ability to have same cache for same queryKey.

staleTime - works, if we change it for 2nd response. But also looks like workaround (not obvious, imho).

But I'm trying to understand why onSuccess instance handler depends on queryKey. Why it couldn't be uniq and fires only for appropriate request?

Thanks for the response.

sshmyg avatar Mar 15 '21 10:03 sshmyg

it is not depending on the queryKey, sorry for the confusion. I changed my initial response and stroke through the "wrong" answers, did you see that?

onSuccess depends on the observer. one component can say: I want to use the query, and when fetching is successful, I want to do something, and the other component can say: after fetching, I want to do something else (or nothing at all if there is no onSuccess callback).

staleTime - works, if we change it for 2nd response.

no, staleTime is unique per query. If one observer has 0 and the other has 10, it is still 0. That is why custom hooks are the preferred abstraction - it doesn't make much sense to define different staleTimes per observer on the same query. If you use the ReactQueryDevtools, you can see when a query is stale and when not.

No, I would like to have uniq onSuccess

to do what exactly please?

TkDodo avatar Mar 15 '21 11:03 TkDodo

Uniq I meant, fires onSuccess only if current useQuery did request. If some others useQuery instances with same queryKey etc (inside react app) makes request, it doesn't fire any onSuccess from useQuery with same queryKey etc.

As you see from the codebox, second useQuery triggers onSuccess from 1st useQuery and it own. In my opinion this situation is implicit, and if it's not a bug, than it should be described in doc.

sshmyg avatar Mar 15 '21 11:03 sshmyg

As you see from the codebox, second useQuery triggers onSuccess from 1st useQuery and it own.

I don't think that you can trace back one fetch to a single useQuery instance. fetches happen for various reasons, e.g. window focus. There is no real "origin" of those. When data is fetched, all observers are informed, and all onSuccess callbacks are triggered because there is now new data.

if you want to perform side-effects on a per-observer level, maybe a useEffect in a component with [data] as dependency is what you are looking for?

TkDodo avatar Mar 15 '21 11:03 TkDodo

@TkDodo useEffect works. But why I need to seeking some others ways, and not use onSucces. All you've described works staleTime, useEffect, and some others approaches. But question is why onSuccess triggers twice but obviously should just once.

sshmyg avatar Mar 15 '21 11:03 sshmyg

But question is why onSuccess triggers twice but obviously should just once.

maybe there are other opinions on this as well, but why should it "obviously" only be called once? You have the reasoning that mounting your component2 "triggers" the fetch, and that's why only the callbacks of component2 should be called. According to the docs:

This callback will fire any time the query successfully fetches new data.

both observers point to the same query - the same data in the cache. Why should only one be informed that there is now new data and not the other if both observers have an onSuccess callback?

I think it would be quite confusing if we decide to call callbacks conditionally. what if 2 observers mount at the same time, which callbacks should be called? who "triggered the fetch", both of them, or only one. same goes for window focus refetching, or refetching when the network disconnects.

TkDodo avatar Mar 15 '21 12:03 TkDodo

both observers point to the same query - the same data in the cache. Why should only one be informed that there is now new data and not the other if both observers have an onSuccess callback?

Because it's 2 different instances of useQuery. And it's logically that I want to have an ability to handle success separately, imho.

Not call callbacks conditionally. But only for instance that made a request, not for each instances. Confusing that thing, that request was made in one place, but onSuccess fires not only there but also in some others places.

sshmyg avatar Mar 15 '21 13:03 sshmyg

But only for instance that made a request, not for each instances.

I can only repeat: it's not the instance that is making the request :)

To be honest, I've never used the callbacks for queries - only for mutations, since queries can be made many times, even without user interaction. Imo, if you have code that should happen for one observer, I would not use the callbacks for that. But I still don't know what's the actual problem you're trying to solve. Maybe I'm wrong, but I think this is how the callbacks were intended.

TkDodo avatar Mar 15 '21 14:03 TkDodo

@TkDodo Thank you

sshmyg avatar Mar 15 '21 14:03 sshmyg

After carefully reading these comments and after TKDodo helped me understand what happens on Twitter, Thank you very much, this is my take: he wants to grab the data from cache on the Children component use useQuery, because the data is already there from the first onSuccess in the Parent. To not fire a second request on Children which would be a waste somehow. Data is fresh anyway, only the Children render delay. to solve this the best option imo is a custom hook for that key. You call the custom hook in Parent and in Children but that way you only have one key and one onSuccess callback no 2 requests to the server.

bogadrian avatar Jul 24 '22 07:07 bogadrian

Just a random thought. does it work if cacheTime is 0?

coadtan avatar Oct 07 '22 15:10 coadtan

If you're transitioning between react-query, and redux and thought, "hey, I will just dispatch an update action with data from onSuccess react query callback" in your custom useQuery hook that you are reusing, you'll find out it will dispatch your action times the number of observers you have.

For example, if you have 5 observers on the page, you'll dispatch that action 5 times.

Another observation is if you use a select function option, that data argument for the onSuccess callback will be different. This is using ReactQuery v3.

In this case you would be dispatching to an action assuming you had the same data, but in reality the data would be dependent on your select.

magbicaleman avatar Mar 03 '23 18:03 magbicaleman

hey, I will just dispatch an update action with data from onSuccess react query callback

if you're doing that, there is a fundamental misunderstanding in how react-query works, and that is a bigger problem than multiple dispatches. If you are dispatching actions in onSuccess, you are "syncing state", thus creating multiple sources of truth (the redux store + the query cache).

In this case you would be dispatching to an action assuming you had the same data, but in reality the data would be dependent on your select.

TypeScript knows this as types in onSuccess are inferred from the result of select, but yes, that is also on purpose. Don't sync state, derive it.

TkDodo avatar Mar 04 '23 09:03 TkDodo

@TkDodo I do agree that syncing state is not ideal, but for the sake of smooth transitioning from redux/redux-saga this is very convenient. I want to transition in stages, 1st one is just making sure everything works with react-query, afterwards removing the 2nd state (redux). So is there a hack or something to trigger an action or whatever once "reach query is fetching remotely" only once other than OnSuccess mentioned above?

shaygong avatar Mar 07 '23 10:03 shaygong

useEffect

TkDodo avatar Mar 07 '23 11:03 TkDodo

But even a gradual migration from redux to react query doesn't need to be done with state syncing. You have access to the queryClient in sagas, so you can get data from there. In components, you can pass dats from react-query to selectors and combine that with custom hooks...

TkDodo avatar Mar 07 '23 12:03 TkDodo

Unless I'm missing something, useEffect with a dependency of the data (or query) still triggers multiple times. As for the migration, The main point is removing the saga so I don't want to use react-query in there, but since our app is huge, lots of containers using data from the store and relying on actions get called, my simple first task is to create a custom react query hook and call in somewhere inside a specific tab or tabs in my app and use directly it's data, but others places should be synced with this data and currently my only option is to sync it to the store until I remove one by one to use the data from the query (or my custom hook using that query rather).

shaygong avatar Mar 07 '23 12:03 shaygong