Deployment
Interacting with your Embeddable

Interacting with your Embeddable

You can interact with your <em-beddable> as if it is a part of your own codebase.

Pass In and Update Variables

You can pass in variables to your Embeddable by passing a variables attribute in your web component that contains an arbitrary JSON string. You can also update these variables in response to actions in your app. This will cause the Embeddable to refresh and display data based on the new variable values.

Here is an example of passing variables from a simple client app to your Embeddable:

const securityToken = await getSecurityTokenFromYourBackend();
const variables = {
  'Country': 'Germany',
  'Date range': { from: new Date(2024, 1, 12), to: new Date() }
};
// Embeddable React component defined as per example below
<Embeddable token={securityToken} variables={variables} />

If you're not using a React wrapper, you can pass variables directly to the web component like this:

<em-beddable
  token="YOUR_SECURITY_TOKEN_HERE"
  variables='{"Country": "Germany", "Date range": {"from": "2024-02-12T00:00:00.000Z", "to": "2024-06-01T00:00:00.000Z"}}'
></em-beddable>

Note that variable names must exactly match the variable names defined in your dashboard. You can learn more about dashboard variables here.

If you update these variables in your client application, the Embeddable will refresh and display data based on the new values. For example, you could have a dropdown in your app that allows users to select a country, and when they select a new country, you update the Country variable in your Embeddable.

This flow is bi-directional. If a user interacts with the dashboard and changes a variable (e.g., by using a filter), you can listen to these changes in your app (see below).

Listen to Variable Changes

You can listen to variable changes in your Embeddable by adding an event listener for the variablesChange event. This event is fired each time a variable inside your Embeddable updates (e.g., user selects a new country). The event detail contains an array of objects with the variable name and its new value.

Here is an example of how to listen to variable changes in your Embeddable:

const handleVariableChange = (e) => {
  console.log('Variables changed:', e.detail);
};
const embeddableElement = document.querySelector('em-beddable');
embeddableElement.addEventListener('variablesChange', handleVariableChange);

Listen to Component Events

Components fire their own events as users interact with them — a bar chart when a bar is clicked, a table when a row is clicked, a dropdown when a value is picked. In the builder, these events are usually connected to a variable so that the rest of the dashboard reacts to them. You can also listen to them directly in your app with the componentEvent event, and let a dashboard interaction drive your own UI instead — opening a report, navigating to another page, or updating something outside the Embeddable.

The event's detail property contains:

PropertyDescription
eventNameThe event the component fired, as named in its meta.events (e.g. onBarClicked).
componentIdThe component that fired it.
componentNameThe type of that component (e.g. BarChartStackedPro).
valueThe event's properties, as declared in meta.events[].properties. A property the user cleared arrives as null.
isDrillDowntrue when the event comes from an Embeddable opened in a drill-down modal.

Here is an example of how to listen to component events in your Embeddable:

const handleComponentEvent = (e) => {
  if (e.detail.eventName === 'onBarClicked') {
    navigateTo(`/reports/${e.detail.value.axisDimensionValue}`);
  }
};
const embeddableElement = document.querySelector('em-beddable');
embeddableElement.addEventListener('componentEvent', handleComponentEvent);

Every event a component fires reaches your listener, whether or not it is connected to a variable, and any interactions you have already configured in the builder keep working alongside it. Unlike a variable, an event is not state: a user clicking the same bar twice fires componentEvent twice, even though the value has not changed.

Which events a component fires, and what each one puts in value, is defined by the component itself. If you build your own components, you declare both in your .emb.ts file.

đź’ˇ

If you embed more than one Embeddable on a page, event.target is the <em-beddable> element the event came from, so you can tell them apart by listening on each element separately. The one exception is drill-down: a dashboard opened in a drill-down modal reports against the element it was opened from, which is what isDrillDown is there to distinguish.

Handle Component Errors

You can listen to errors that occur in your Embeddable by adding an event listener for the onEmbeddableError event. This event is fired each time an error occurs in your Embeddable (e.g., network error, invalid token). The event's detail property contains an object with the error message and error detail.

Here is an example of how to listen to errors in your Embeddable:

const handleEmbeddableError = (e) => {
  console.error('Embeddable error:', e.detail);
};
const embeddableElement = document.querySelector('em-beddable');
embeddableElement.addEventListener('embeddableError', handleEmbeddableError);

You can use this to log errors, show error messages to users, or take other actions in response to errors. You could also use this to send the error details to your back-end for further processing, such as alerting or logging.

Know When Components are Loaded

You can listen to when your Embeddable has finished loading its components by adding an event listener for the onComponentsLoad event. This event is fired each time the Embeddable has finished loading all its components (e.g., charts, tables). This can be useful for showing a loading spinner while the Embeddable is loading, and then hiding it once the components are ready.

This event fires once all of the Embeddable's components have loaded and rendered, but each component may still be in an individual loading state, as this event does not wait for any loadData requests to return.

Here is an example of how to listen to the components load event in your Embeddable:

const handleComponentsLoad = () => {
  console.log('Embeddable components have loaded');
};
const embeddableElement = document.querySelector('em-beddable');
embeddableElement.addEventListener('componentsLoad', handleComponentsLoad);

Know When Pre-aggregations are Building

When a component requests data that isn't covered by an existing pre-aggregation, Cube builds that pre-aggregation on-demand before it can return results, which may take some time. This typically happens after a data import, or for a security context that has not been configured via the Caching API.

You can listen for the preAggregation event to tell your users that their data is still being prepared, rather than leaving them looking at a dashboard that appears to be stuck.

The event's detail property contains:

PropertyDescription
statusstarted, completed or failed (see below).
componentIdThe component whose data request triggered the build.

Each data request fires started at most once, followed by exactly one terminal event:

  • started: the request has triggered a pre-aggregation build.
  • completed: the request returned its data, so the build it was waiting on has finished.
  • failed: the request did not complete. Either it errored, or it was superseded by a newer request (for example, because a user changed a filter while the build was still running).

Here is an example of how to listen to pre-aggregation builds in your Embeddable:

const handlePreAggregation = (e) => {
  if (e.detail.status === 'started') {
    showMessage('Preparing your data. This may take a few moments.');
  } else {
    hideMessage();
  }
};
const embeddableElement = document.querySelector('em-beddable');
embeddableElement.addEventListener('preAggregation', handlePreAggregation);
đź’ˇ

Several components can trigger builds at the same time. Because every started is followed by exactly one completed or failed, you can show a single message for the whole dashboard by keeping a count: add one on started, subtract one on either terminal status, and show your message while the count is above zero.

Pass Client Context

Client Context allows you to pass information about the user or environment to your React components. This is accomplished by passing a client-context attribute in your web component that contains an arbitrary JSON string. This can be useful for localization, theming, or other context-specific behavior. You can learn more here, including detailed examples.

Complete Example

Here is a complete example of a React wrapper component (Dashboard) that uses the Embeddable component and demonstrates all of the above features. Note that the Dashboard component passes in callback functions to handle variable changes, component load events, and errors, while the Embeddable component wires up the event listeners to the web component.

First is the main Dashboard component that uses the Embeddable component:

import React from 'react';
import Embeddable from './Embeddable';
 
type Props = {
  securityToken: string;
};
 
const Dashboard: React.FC<Props> = ({ securityToken }) => {
  const [isLoading, setIsLoading] = React.useState(true);
  const [variables, setVariables] = React.useState({
    Country: 'Germany',
    'Date range': { from: new Date(2024, 1, 12), to: new Date() },
  });
 
  return (
    <>
      {isLoading && <div>Loading...</div>}
      <Embeddable
        token={securityToken}
        variables={variables}
        onVariablesChange={setVariables}
        onEmbeddableError={(e) => {
          console.log(`${e.errorMessage} : ${e.errorDetail}`);
        }}
        onComponentsLoad={() => setIsLoading(false)}
        clientContext={{ locale: ['en-US'], language: 'en', darkMode: false }}
      />
    </>
  );
};
 
export default Dashboard;

Below is the Embeddable component, which wraps <em-beddable> and wires up event listeners - its helper functions then use the callback props passed from the Dashboard component:

import React, { type Dispatch, type SetStateAction } from 'react';
 
type Props = {
  token: string;
  onComponentsLoad: (e: any) => void;
  variables: Record<string, any>;
  onVariablesChange: Dispatch<
    SetStateAction<{ Country: string; 'Date range': { from: Date; to: Date } }>
  >;
  onEmbeddableError: (error: any) => void;
  clientContext: Record<string, any>;
};
 
type Detail = {
  variableName: string;
  newValue: any;
};
 
const Embeddable: React.FC<Props> = ({
  token,
  onComponentsLoad,
  variables,
  onVariablesChange,
  onEmbeddableError,
  clientContext,
}) => {
  const ref = React.useRef<any>(null);
 
  function handleVariableChange(e: { detail: Detail[] }) {
    if (onVariablesChange) {
      onVariablesChange(
        Object.fromEntries(
          e.detail.map((c: any) => [c.variableName, c.newValue]),
        ),
      );
    }
  }
 
  function handleEmbeddableError(e: any) {
    onEmbeddableError(e.detail);
  }
 
  React.useEffect(() => {
    if (ref.current) {
      ref.current.addEventListener('variablesChange', handleVariableChange);
      ref.current.addEventListener('componentsLoad', onComponentsLoad);
      ref.current.addEventListener('embeddableError', handleEmbeddableError);
 
      return () => {
        ref.current?.removeEventListener(
          'variablesChange',
          handleVariableChange,
        );
        ref.current?.removeEventListener('componentsLoad', onComponentsLoad);
        ref.current?.removeEventListener(
          'embeddableError',
          handleEmbeddableError,
        );
      };
    }
  }, []);
 
  return React.createElement('em-beddable', {
    ref,
    token,
    'client-context': JSON.stringify(clientContext),
    variables: JSON.stringify(variables),
  });
};
 
export default Embeddable;

How This Helps:

  • Track variable changes: Each time variables inside your Embeddable update (e.g., user selects a new country), the variablesChange event fires, and you can respond in your app.
  • Control filters/state: By calling onVariablesChange, you can update local React state and trigger data refreshes or other UI logic.
  • Handle load states & errors: The onComponentsLoad event indicates Embeddable has finished loading components, and onEmbeddableError captures issues like network problems or invalid tokens.