Introduction

When working with a Product Page, it’s common for data to reside outside of Sitecore. In such cases, the CMS may only hold a reference ID to the actual data stored in another system. A typical page is composed of numerous components, and using getStaticProps for each component can result in multiple API calls, leading to inefficiency.

Solution

To address this issue, you can use a Page Props Factory Plugin. This plugin allows you to manage data fetching more efficiently by centralizing API calls.

Step-by-Step Guide

Create a New File

Navigate to /lib/page-props-factory/plugins and create a new file named product-props.ts.

Step 2: Add the Following Code


class ProductPropsPlugin implements Plugin {
  private productService: ProductService;

  order = 4;

  constructor() {
    this.productService = new ProductService();
  }

  async exec(props: SitecorePageProps) {
    if (!props.layoutData.sitecore.route) return props;
    if (props.layoutData.sitecore.route.templateId != PRODUCT_DETAIL_PAGE
      return props;

    const route = props.layoutData.sitecore.route;
    const productIdField = route.fields?.productId as Field<string>;
    if (productIdField.value === '') return props;
   
    const productResponse = await this.productService.getProduct(
      productIdField.value as string
    );

    const componentProps = props.componentProps as { [key: string]: unknown };
    componentProps['productData'] = productIdField.data.product;

    const errors = Object.keys(props.componentProps)
      .map((id) => {
        const component = props.componentProps[id] as ComponentPropsError;

        return component.error
          ? `\nUnable to get component props for ${component.componentName} (${id}): ${component.error}`
          : '';
      })
      .join('');

    if (errors.length) {
      throw new Error(errors);
    }

    return props;
  }
}

export const productPropsPlugin = new ProductPropsPlugin();

Step 3: Use the Property in Your Component

Finally, you can add the following code in your component to get the property:

const productData = useComponentProps<Product>('productData') as Product;

Conclusion

By implementing a Page Props Factory Plugin, you can optimize API calls for a page with multiple components. This approach reduces redundancy and improves performance by centralizing data fetching, making your application more efficient and maintainable.