We need a function that may call an API or the other, and based on the result, call yet another API.
Let me give a simplified example. We're trying to do something like this
function getCarDetails(car: CarSummary): UseQueryResult<CarDetails> {
if(car.make === 'honda') {
const hondaResponse = useHondaData(car);
if(hondaResponse.isError)
return hondaResponse;
return useCarDetailsData(
{x: hondaResponse.data?.y},
{enabled: !!hondaResponse.data}
);
}
else if(car.make === 'tesla') {
const teslaResponse = useTeslaData(car);
if(teslaResponse.isError)
return teslaResponse;
return useCarDetailsData(
{x: teslaResponse.data?.y},
{enabled: !!teslaResponse.data}
);
}
else {
return useCarDetailsData(
{x: 'generic'},
{enabled: true}
);
}
}
The above code would be ideal, if only hooks can be called from inside if
s.
But as hooks can only be called from the top level, what is the best way to achieve the above (i.e. nested/conditional chained API calls using React Query)?