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.
- A Storefront Next app created in Business Manager, which includes a SLAS client set up automatically for authorization to Shopper APIs. See Create a Storefront in Business Manager with Local Code or Explore Storefront Next Code Locally.
- A custom page created in Add a Page and a Component.
- An Integrated Development Environment (IDE), such as VS Code, Cursor, or your favorite IDE. See Download VS Code or Download Cursor.
-
Create a
FeaturedProductscomponent that renders a grid of products.a. In
{project-folder}/src/components, create a folder namedfeatured-products.b. In the new
featured-productsfolder, createindex.tsxwith this code.FeaturedProductsaccepts aproductsarray and an optionaltitle. It renders a responsive grid of product cards, each showing the product image, name, and price. -
Add a loader to the custom page route to fetch products from B2C Commerce. Open
{project-folder}/src/routes/_app.custom-page.tsxand replace its contents with this code.The
loaderfunction runs on the server before the page renders.createApiClients(context)returns all Shopper API clients configured for the current site. ThecreateApiClientsfunction is a template wrapper around the framework’screateCommerceApiClientsfunction.createApiClientsreads 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 querydressand destructuresdatafrom the response. The results are mapped to theProducttype and returned asloaderData.CustomPageViewreceivesloaderDataas a prop and passes the products toFeaturedProducts.CustomPageDatais derived directly from the loader’s return type, so the component stays in sync with the data shape automatically. -
In a terminal window, go to the storefront folder.
-
Build the storefront and run the development server.
-
Navigate to
http://localhost:5173/custom-page. The page now shows the banner followed by a grid of products fetched from B2C Commerce.
