Parallelize data fetching
Learn how to parallelize data fetching in your application.
If you need to execute multiple GraphQL queries in a single loader, you can
parallelize them using
Promise.all
.
You can use any promise that returns data, not only GraphQL queries.
Here's an example of a loader that fetches data from a GraphQL query and an external API package:
Before:
app/routes/data-route.tsx
import { FrontCommerceApp } from "@front-commerce/remix";
import { json } from "@front-commerce/remix/node";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { MyFirstQueryDocument, MySecondQueryDocument } from "~/graphql/graphql";
import externalApi from "@example-package/external-api";
export async function loader({ context }: LoaderFunctionArgs) {
const app = new FrontCommerceApp(context.frontCommerce);
const firstData = await app.graphql.query(MyFirstQueryDocument);
const secondData = await app.graphql.query(MySecondQueryDocument);
const externalData = await externalApi.fetchData();
return json({
firstData,
secondData,
externalData,
});
}
After:
app/routes/data-route.tsx
import { FrontCommerceApp } from "@front-commerce/remix";
import { json } from "@front-commerce/remix/node";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { MyFirstQueryDocument, MySecondQueryDocument } from "~/graphql/graphql";
import externalApi from "@example-package/external-api";
export async function loader({ context }: LoaderFunctionArgs) {
const app = new FrontCommerceApp(context.frontCommerce);
const [firstData, secondData, externalData] = await Promise.all([
app.graphql.query(MyFirstQueryDocument),
app.graphql.query(MySecondQueryDocument),
externalApi.fetchData(),
]);
return json({
firstData,
secondData,
externalData,
});
}
tip
Please note that in this case, our API calls are independent from each other, so they will be executed in parallel. But you can also play with promises, to chain API calls.
warning
This is a simple example. In a real-world scenario, make sure to handle errors properly.