apollo-client-nextjs icon indicating copy to clipboard operation
apollo-client-nextjs copied to clipboard

Best Approach for Prefetching Multiple Queries in Apollo with Next.js?

Open naimulemon opened this issue 1 year ago • 1 comments

I’m working with Apollo Client in a Next.js 14 project and trying to prefetch multiple GraphQL queries using PreloadQuery. I want to ensure that this is the correct approach for prefetching multiple queries and handling the data efficiently within the component.

const IndexPage: React.FC = () => {
  return (
    <>
      <ApolloWrapper>
        <PreloadQuery query={ProductDocument}>
          <PreloadQuery
            query={gql(`query ProductDiscount($productId: Int!) {
  productDiscount(productId: $productId) {
    id
    discount
    offerTitle
  }
}`)}
          >
            <Suspense fallback={<div>Loading...</div>}>
              <ProductComponent />
            </Suspense>
          </PreloadQuery>
        </PreloadQuery>
      </ApolloWrapper>
    </>
  );
};

Is this a recommended way to prefetch multiple queries using PreloadQuery? Are there more efficient or cleaner alternatives for handling multiple queries in this scenario, particularly with regards to code readability and performance?

naimulemon avatar Oct 09 '24 19:10 naimulemon

The general advice would be to use fragment colocation to compose all your data needs into one query, but if you are using more than one query per router, you're already doing it right.

phryneas avatar Oct 10 '24 07:10 phryneas

Do you have any feedback for the maintainers? Please tell us by taking a one-minute survey. Your responses will help us understand Apollo Client usage and allow us to serve you better.

github-actions[bot] avatar Oct 12 '24 20:10 github-actions[bot]