Add a Component That Fetches Data

Extend a Storefront Next page to fetch data on the server and pass it to a React component. This guide builds on Add a Page and a Component by adding a server-side loader that retrieves products from B2C Commerce and renders them in a new component.

  1. Create a FeaturedProducts component that renders a grid of products.

    a. In {project-folder}/src/components, create a folder named featured-products.

    b. In the new featured-products folder, create index.tsx with this code.

    FeaturedProducts accepts a products array and an optional title. It renders a responsive grid of product cards, each showing the product image, name, and price.

  2. Add a loader to the custom page route to fetch products from B2C Commerce. Open {project-folder}/src/routes/_app.custom-page.tsx and replace its contents with this code.

    The loader function runs on the server before the page renders. createApiClients(context) returns all Shopper API clients configured for the current site. The createApiClients function is a template wrapper around the framework’s createCommerceApiClients function. createApiClients reads site configuration, credentials, and locale from context and sets up authentication automatically so you don’t need to pass those values manually. The loader calls the Shopper Search API to retrieve four products matching the query dress and destructures data from the response. The results are mapped to the Product type and returned as loaderData. CustomPageView receives loaderData as a prop and passes the products to FeaturedProducts. CustomPageData is derived directly from the loader’s return type, so the component stays in sync with the data shape automatically.

  3. In a terminal window, go to the storefront folder.

  4. Build the storefront and run the development server.

  5. Navigate to http://localhost:5173/custom-page. The page now shows the banner followed by a grid of products fetched from B2C Commerce.

Custom page shows the featured products that are fetched with the Shopper API