ADA Chat with ReactJS & NextJS - problem with initialisation when go to other screen

Viewed 25

We are using ADA chatbot with ReactJS and NextJS, but we are facing problems when we go to another page, and the chat closes. Let's say we have 3 pages A,B,C and only on 2 of them we want to have with a chat bubble. So what I have done is include simple Chat start/stop logic (note: dynamic next import because of client-side rendering).

debug implementation of Chat

import { FC, useEffect, useRef } from 'react';
import adaEmbed from '@ada-support/embed2';
/**
 * warn: in Next.js this must be loaded dynamically only on client side  - how to:
 *
 * import dynamic from 'next/dynamic';

 * const Chat = () => {
 *     const Chat = dynamic(() => import('components/Chat'), {
 *         ssr: false,
 *         loading: () => <div>loading</>,
 *     });
 *     return <Chat />;
 * };
 */
const Chat: FC<{ caller: string }> = ({ caller }) => {
    useEffect(() => {
        console.log('mounting:', caller);
        adaEmbed
            .start({
                handle: 'HANDLE',
            })
            .then(() => {
                console.log('started:', caller);
            })
        return () => {
            console.log('unmounting:', caller);
            adaEmbed
                .stop()
                .then(() => {
                    console.log('stopped', caller);
                })
        };
    }, [caller]);
    return null;
};

export default Chat;

Now what's happening when going from A -> B is this:

mounting A
started A
unmounting A
mounting B
started B
stopped A

So the starting function from B is quicker than stopping from A. We need to stop it somewhere as we don't want to run it on page C.

Have you anybody implemented ADA chat with such a setup? Any tips&tricks or different approaches?

1 Answers

Try rewriting the useEffect return function this way:

    return async () => {
                console.log('unmounting:', caller);
                await adaEmbed
                    .stop();
                console.log(‘stopped’, caller);
            };
Related