Communication between components¶
To enable communication between the app components and the Alan AI 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 dialog script with Alan AI’s callProjectApi() method when a button in the app is clicked. For that, you need to:
Send the
call-project-api
event from the button component with thedispatchEvent()
method: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 dialog script</button>; }; export default Button;
In the Alan AI button wrapper, register an event listener to listen for the
call-project-api
event and call themyApi
callProjectApi() method defined in the dialog script: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.