T
TanStack10mo ago
solid-orange

Queue invalidation without aborting in-flight requests

I have key parts in my app where queries sometimes (in bursts) can invalidate faster than the async queryFn can return fresh data. React-query will provide a pretty bad user experience in this case potentially showing the user stale data for minutes, as it will (on every invalidateQueries call) try to abort in-flight requests, ignores their results and just calls queryFn again. Instead, it's way better to not abort the current request but await it, update the data and queue another refetch to be run after that. This way the user will see data that's pretty much up-2-date. I'm currently using a custom implementation to do that. Is there an easy to achieve this using react-query? I even feel that this should be the default lib behaviour - cause most of the time there is no point in aborting in-flight requests. Edit: didn't verify the behaviour but RTKQs invalidationBehaviour 'delayed' sounds about what I want to achieve with react-query https://redux-toolkit.js.org/rtk-query/api/createApi#invalidationbehavior
createApi | Redux Toolkit
RTK Query > API: createApi reference
3 Replies
extended-salmon
extended-salmon10mo ago
I think you can just not use the abort signal passed to the queryFn, and then it will behave like you describe (I'm not 100% sure tho so needs testing)
solid-orange
solid-orangeOP10mo ago
RQ still ignores the result and directly fires a new request.
funny-blue
funny-blue10mo ago
Instead, it's way better to not abort the current request but await it, update the data and queue another refetch to be run after that.
I think this could lead to lots of requests being "queued up", for example when you do concurrent mutations. I think what you should be doing is not fire invalidateQueries if the query is already fetching. "queuing" an invalidation is not something we support out of the box, but is something you could build on your own on top of the e.g. useIsFetching hook, or by taking the promise from the query cache and awaiting it.

Did you find this page helpful?