The dispatch method helps us communicate between different components through a function as a parameter.

We’ll be using the dispatch method quite often, so this documentation will help you familiarize yourself with it.

Please read the below disclaimer before getting started ⬇️

<aside> 🔔 IMPORTANT

The data and dispatch should not be used to hold local state for a component. Performing a dispatch call re-renders the component and will create performance issues as well as loss of state in some instances.

</aside>


As an example, let’s imagine a straightforward app that consists of printing your full name on a page.

For that, we must configure two key details:

  1. the way we’ll ask about the user’s full name, and
  2. where we'll be collecting the printed full name.

<aside> 🔔 IMPORTANT

Note that this example shows overrideControls as a method called from Schema.string(). Methods like these or similar that update the way controls are appended via the schema instance will soon be deprecated.

See “Controls” section in this article to create new controls or use pre-registered controls.

</aside>

Here’s a sample code to illustrate the above points:

const ControlComponent = ({dispatch}: any) => {
  // We declare this method that is intended to be used by our component.
  const onChange = (fullName: string) => {
    // As we explained, we need to communicate this data received to show them
    // on the SmartBuilder page.
    dispatch((api: any) => {
      // Here we are updating the schema with the user input.
      api.get('fullName').set(fullName);
    });
  };

  return '<<your component or your HTML element>>'
}

const MyComponent = ({data}: any) => {
  // Retrieves the fullName property value from the Schema
  const { fullName } = data;
  // Returns the component or HTML element to be shown on the SmartBuilder page.
  return (<span>Hey ${ fullName }, what's up!</span>);
}

{
  componentTypeId: "showFullName",
  displayName: "ShowFullName",
  schema: Schema.object({
    fullName: Schema.string().overrideControls([{
      Control: ControlComponent,
      options: {
        icon: <span>C</span>,
        label: 'Configuration'
      }
    }]),
    Component: MyComponent
  })
}