Chaining API requests react query v3
Hey Team,
I want to chain an API request so that the first one have to complete then the second one should start. This scenario can happen multiple times. So I need to run the powQuery multiple times and I need the behaviour that this one is the first one.
My idea is to use a state which I set onSettled
Request 1, which needs to run first:
const queryClient = useQueryClient();
const [powerSettled, setPowerSettled] = useState<boolean>(false);
const powQuery = ({
queryKey: ["power", { roundId }, params],
queryFn: () => {
setEnergyConsumptionSettled(false); // while fetch set to false
return getRouteRemainingEnergy(routeId, params)
},
onSettled: () => setPowerSettled(true),
}
};
in request 2 I would like to use powerSettled as enabled. Would that be a good way to do it? I just want to make sure that fetch 1 is completed before fetch 2 starts.
Request2:
.....
enabled: powerSettled
1 Reply
correct-apricot•4y ago
Why not just do this?
https://tanstack.com/query/v4/docs/guides/dependent-queries
Dependent Queries | TanStack Query Docs
Dependent (or serial) queries depend on previous ones to finish before they can execute. To achieve this, it's as easy as using the enabled option to tell a query when it is ready to run:
`tsx