T
TanStack3y ago
rival-black

Is it a good idea to call multiple API's from the loader function?

I am working on a Solo Project, making a Crypto Directory Project. I need to call multiple API's on more then one pages to collect data, is it preferrable to call more than one API from the loader function instead of calling them inside your component. PS: I am using TypeScript, would love to hear your thoughts on the return type of the loader function and tips to avoid warnings and error while coding.
5 Replies
ambitious-aqua
ambitious-aqua3y ago
If the data you need in the frontend has to be aggregated from multiple APIs, you can create an async function that calls all these APIs (either in parallel with Promise.all() or sequentially if the requests depend on each other) and call that function either in the route loader (assuming by loader you mean react router or remix route loader) or in useQuery's queryFn.
rival-black
rival-blackOP3y ago
Yeah your are right by loader I mean for the one by react router. Could you please elaborate more, I am unable to digest what you have written. Let me rephrase what you have written. I should make an async function and call them when I am trying to mount the component which is going to consume those data, and I should invoke this function from the route loader function. ?
ambitious-aqua
ambitious-aqua3y ago
Check out this article for how to use react router and react query together: https://tkdodo.eu/blog/react-query-meets-react-router In your case, you need to call multiple APIs instead of one but you can put all the API calls inside a single function, and call that function as if it were a single API:
const callAllMyApis = async () => {
await callApi1();
await callApi2();
await callApi3();
}
const callAllMyApis = async () => {
await callApi1();
await callApi2();
await callApi3();
}
Or
const callAllMyApis = async () => {
await Promise all(callApi1(), callApi2(), callApi3());
}
const callAllMyApis = async () => {
await Promise all(callApi1(), callApi2(), callApi3());
}
React Query meets React Router
React Query and React Router are a match made in heaven.
rival-black
rival-blackOP3y ago
Alright Thanks I will read through, if I stuck at some point, can I ask for you help.? @julien
ambitious-aqua
ambitious-aqua3y ago
Sure, you can use this thread.

Did you find this page helpful?