Home > widget-integration > RecommendationWidgetController > handleWidgetInViewport

RecommendationWidgetController.handleWidgetInViewport() method

Handles the complete widget lifecycle when it enters the viewport.

This method orchestrates the entire widget rendering process: fetching data, handling loading states, managing empty states, rendering the widget, and cleaning up the observer. Override this method to customize the entire widget lifecycle or add custom analytics, logging, or error handling.

Signature:

protected handleWidgetInViewport(widgetId: string, parent: HTMLElement, unobserve: () => void): Promise<void>;

Parameters

Parameter

Type

Description

widgetId

string

The unique identifier of the widget to render

parent

HTMLElement

The parent HTML element where the widget will be rendered

unobserve

() => void

Callback function to stop observing the element after rendering

Returns:

Promise<void>

Exceptions

{Error} When widget rendering fails due to network, template, or DOM errors

Remarks

The method follows this lifecycle: 1. Set loading state to true 2. Fetch recommendation data 3. Set loading state to false 4. Handle empty recommendations (remove widget) 5. Update state with model 6. Render widget 7. Execute post-render hooks 8. Stop observing element

Error handling: Errors during rendering will propagate to the caller. Consider wrapping this method in a try-catch block when extending.

Example

Override to add custom analytics tracking:

protected async handleWidgetInViewport(widgetId, parent, unobserve) {
  // Track widget impression
  this.analytics.trackImpression('recommendation_widget', { widgetId });

  try {
    await super.handleWidgetInViewport(widgetId, parent, unobserve);
    this.analytics.trackSuccess('widget_rendered', { widgetId });
  } catch (error) {
    this.analytics.trackError('widget_failed', { widgetId, error });
    throw error;
  }
}