Skip to main content

Custom Hooks

The following is an example for using custom hooks, which allows you to interact with the chatbot functionalities externally (i.e. from your own components). The full list of hooks and the functionalities they expose can be found here. For this example, we'll only be looking at a few hooks such as useAudio, useFlow, useToasts and useNotifications. The hooks are imported within the MyChatBotWrapper component which is nested under ChatBotProvider.

Live Editor
const MyChatBotWrapper = () => {
    const { toggleAudio } = useAudio();
    const { restartFlow } = useFlow();
    const { showToast } = useToasts();
    const { playNotificationSound } = useNotifications();

    const settings = {
        general: {embedded: true},
        chatHistory: {storageKey: "example_custom_hooks"},
        botBubble: {simStream: true},
        audio: {disabled: false}
    }

    const flow={
        start: {
            message: "Welcome to the playground 🥳! Edit and experiment as you wish!",
            path: "end_loop"
        },
        end_loop: {
            message: (params) => `Received: ${params.userInput}`,
            path: "end_loop"
        }
    }

    return (
        <>
          <ExampleButton onClick={toggleAudio} text="Click me to toggle audio!"/>
          <ExampleButton onClick={restartFlow} text="Click me to reset the flow!"/>
          <ExampleButton onClick={() => showToast("Hello there!")} text="Click me to show a toast!"/>
          <ExampleButton onClick={playNotificationSound} text="Click me to play a notification sound!"/>
          <ChatBot settings={settings} flow={flow}/>
        </>
    );
};

const MyChatBotProvider = () => {
    return (
        <ChatBotProvider>
            <MyChatBotWrapper/>
        </ChatBotProvider>
    );
};

// button to test above feature
const exampleButtonStyle = {
    backgroundColor: '#491D8D',
    color: 'white',
    border: 'none',
    padding: '10px 20px',
    textAlign: 'center',
    textDecoration: 'none',
    display: 'inline-block',
    fontSize: '16px',
    borderRadius: '5px',
    cursor: 'pointer',
    transition: 'background-color 0.2s',
    margin: 10,
};
const ExampleButton = (props) => {
    return (
        <button onClick={props.onClick} style={exampleButtonStyle}>{props.text}</button>
    );
};

render(<MyChatBotProvider/>)
Result
Loading...