I'm trying to build a small widget with some inputs and cards that contain data which is recalculated on the backend using react and apollo. Cards contain a loader to indicate that request is in progress.
Whenever I change an input, I want to trigger a request to backend, which takes a long time (due to computation) - around 30 seconds.
When you input data - mutation is triggered via one apollo client, but right afterwards it triggers a query to another apollo client, which takes 30 seconds or so.
In that time it is possible to update input again - and in that case, I would like to cancel the previous request and trigger a new one.
This is the query
const {
data,
loading,
refetch,
networkStatus,
} = useCalculationQuery({
widget_id: widgetId,
skip: !isCalcTriggered,
});
Code for useCalculationQuery
function useCalculationQuery({ widget_id, skip }: Options = {}) {
const { teamId } = ... ;
const query = useQuery(QUERY_CALCULATION, {
skip,
fetchPolicy: 'network-only',
variables: {
team_id: teamId,
widget_id,
},
client: apolloCalculations,
});
return query;
}
And this is the fetch function
async function handleCalcFetch() {
if (isCalcTriggered) {
setIsFetchInProgress(true);
await refetch();
setIsFetchInProgress(false);
}
if (!isCalcTriggered) {
setIsCalcTriggered(true);
}
}
As you can see - with isCalcTriggered flag I skip the query execution until handleCalcFetch is called. Then I set the flag, and on every other call except the first I do refetch.
These other flag (isFetchInProgress which is set with setIsFetchInProgress) is to indicate that request is in place, because after calling refetch, networkStatus is always 7 rather than 4. That's issue number one.
Issue number two is that I want to cancel previous requests whenever I hit refetch(), so that I am sure I always get the newest data, which now is not the case.