Communication between components

To enable communication between the app components and the Alan button wrapper, we recommend that you send events from your components and set up event listeners in AlanBtn.tsx.

For example, you want to send some data to the voice script with Alan’s callProjectApi() method when a button in the app is clicked. For that, you need to:

  1. Send the call-project-api event from the button component with the dispatchEvent() method:

    Button.tsx
    import React, { useCallback, useEffect, useRef } from 'react';
    
    const Button: React.FC = (props: any) => {
      const callProjectApi = useCallback(() => {
        window.dispatchEvent(new CustomEvent("call-project-api", { detail: { data: 'some-data' } }));
      },[]);
      return <button onClick={callProjectApi}>Send data to the voice script</button>;
    };
    
    export default Button;
    
  2. In the Alan button wrapper, register an event listener to listen for the call-project-api event and call the myApi callProjectApi() method defined in the voice script:

    AlanBtn.tsx
    import React, { useEffect, useRef } from 'react';
    import { withRouter } from 'react-router';
    
    const AlanBtn: React.FC = (props: any) => {
      const alanBtnComponent = useRef<any>(null);
    
      useEffect(() => {
        window.addEventListener('call-project-api', (e: any) => {
          alanBtnComponent.current.callProjectApi(
            'myApi',
            e.detail.data,
            (e: any, r: any) => {
              alert('Project API was called');
            }
          );
        });
      }, []);
    
      return (
        <alan-button
          ref={alanBtnComponent}
          alan-key="YOUR_KEY_FROM_ALAN_STUDIO_HERE"
        />
      );
    };
    
    export default withRouter(AlanBtn);
    

Note

For larger projects, you can dispatch actions via Redux or any event-bus JavaScript library.