Skip to content

Error in react bindings (ChatKit showing blank page) #35

@chrille0313

Description

@chrille0313

There is something wrong with the useChatKit() hook or with the <ChatKit /> component. I've setup a basic react project and followed the installation steps in the README.md, but when I go to my page, the chatkit ui is simply blank (see screenshot below):

Image

For reference, here is the corresponding code for that page (should be very close to the example code in the README):

import { ChatKit, useChatKit } from '@openai/chatkit-react';

export default function MyChat() {
  const { control } = useChatKit({
    api: {
      async getClientSecret(existing) {
        console.log('FETCHING SESSION');

        if (existing) {
          // implement session refresh
        }

        const res = await fetch('https://localhost:3000/api/chatkit/session', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        const { client_secret } = await res.json();
        return client_secret;
      }
    }
  });

  return <ChatKit control={control} className="h-[600px] w-[320px]" />;
}

It seems that the getClientSecret() method isn't even being invoked as there is no output in the console.

To fix this, I tried a custom implementation of the chatkit:

import React from 'react';
import type { ChatKitOptions, OpenAIChatKit } from '@openai/chatkit';

export default function Index() {
  const chatRef = React.useRef<OpenAIChatKit | null>(null);

  React.useEffect(() => {
    const el = chatRef.current;
    if (!el) return;

    let disposed = false;

    const options: ChatKitOptions = {
      api: {
        async getClientSecret(existing) {
          console.log('FETCHING SESSION');

          if (existing) {
            // Implement token refresh here if needed
          }

          const res = await fetch('http://localhost:3000/api/chatkit/session', {
            method: 'POST'
          });
          const { client_secret } = await res.json();
          return client_secret;
        }
      }
    };

    customElements
      .whenDefined('openai-chatkit')
      .then(() => {
        if (!disposed) {
          el.setOptions(options);
        }
      })
      .catch((err) => console.error(err));

    return () => {
      disposed = true;
    };
  }, []);

  return <openai-chatkit ref={chatRef} className="h-[600px] w-[320px]" />;
}

which rendered correctly:

Image

This confirms that there must be an issue in one of the two places mentioned in the beginning.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions