Helped needed in Forcing Refetch While RTK Query Request is In-Flight #4988
-
Discussion: Force Refetch While RTK Query Request is In-FlightHi everyone 👋 I'm working on an RTK Query setup where a query endpoint ( I'm using tags to invalidate the polled query when mutations occur. But I've observed 2 behaviours which are slightly problematic to achieve this
This causes practical issues for us, since the query is heavy and takes time to complete. Ideally, I’d like to abort the in-flight query and immediately trigger a new fetch when a mutation occurs. While the tag issue has been widely discussed and i understand there is no solution as of now, the second issue is a bit problematic in this case, because even when i manage to abort the previous APIs, I am guessing there are some sync issues with the state cleanup which indicates if an api is in flight, so ive to use a setTimeout as an escape hatch, as in the code below:- What I’m Trying to Achieve
I’m managing abort controllers manually by extending a custom base query, storing them in a map per endpoint. Here’s what I currently have: function useForcedRefetch({ endpointName, refetch }) {
const [forceRefetchInProgress, setForceRefetchInProgress] = useState(false);
const forceRefetch = () => {
const aborter = abortControllers[endpointName];
if (aborter) {
aborter(); // abort in-flight request
}
// Force a fresh refetch after abortion
setTimeout(async () => {
setForceRefetchInProgress(true);
try {
await refetch().unwrap();
} catch (e) {
console.error(e);
} finally {
setForceRefetchInProgress(false);
}
}, 0); // workaround to avoid refetch() being ignored if query was in-flight
};
return { forceRefetch, forceRefetchInProgress };
} In component
Questions
Final ThoughtsThis works for now, but I’m wondering if there’s a better way to integrate abort → refetch logic, especially in polling scenarios where responsiveness to mutations is important. Any guidance or suggestions are appreciated! Thanks 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Update: rewrote the refetch helper as follows:
|
Beta Was this translation helpful? Give feedback.
Update: rewrote the refetch helper as follows: