Skip to content

getChannelMessages(channelName: string): BaseMessage<unknown>[] | undefined

The getChannelMessages is a method that allows to retrieve an array of past events from a given channel.

Accessing past channel messages is important in many situations, for example:

  • Synchronizing web components that are added to the page after initial load.
  • Restoring the state of web components when users navigate back.
  • Implementing undo/redo capabilities.

NOTE: It is a good practice to ensure all previous events get handled regardless of when a webcomponent gets loaded into the page.

Input parameters

channelName

channelName is a mandatory parameter of the string type which represents the name of the event.

Returned value

A returned value has a type of BaseMessage<unknown>[]. If past events in a given channel do not exist, the returned value is undefined.

Example

In this example we make a messageStorageSystemApi call to retrieve an array of past events.

useStorefront((storefront) => {
    const messageStorageApi = storefront.getApiSync('messageStorageSystemApi');

    const pastStockChangedEvents = messageStorageApi.getChannelMessages('product.stockChanged');

    if (pastStockChangedEvents.length > 0) {
        pastStockChangedEvents.forEach(({ body: eventBody }) => {
            console.log('perform action on every past event');
        });
    }
});

Models reference