Skip to content

queryBus.on

The on method allows to listen to the query similarly to how addEventListener works for DOM events.

Input parameters

messageName

messageName is a mandatory parameter of the string type which represents the name of the message to listen to.

listener

listener is a mandatory parameter of type TMessageListener which represents a callback for the query emission.

Example

To listen to any query emitted by the Query Bus you can use the on method:

useStorefront(async (storefront) => {
    storefront.queryBus.on('example-query', () => {
        console.log('Listening to the query...')
    });
});

Example

Remember that the query bus does not allow two listeners:

useStorefront(async (storefront) => {
    storefront.query.on('example-query', () => {
        console.log('Listening to the query...')
    });

    storefront.queryBus.on('example-query', () => { // Error: Maximum number of listeners reached
        console.log('Listening to the query for the second time...')
    });
});

Listening with on and once at the same time is also not allowed:

useStorefront(async (storefront) => {
    storefront.query.once('example-query', () => {
        console.log('Listening to the query...')
    });

    storefront.query.on('example-query', () => { // Error: Maximum number of listeners reached
        console.log('Listening to the query with on...')
    });
});

Methods reference