MCPcopy
hub / github.com/openai/chatkit-js / useChatKit

Function useChatKit

packages/chatkit-react/src/useChatKit.ts:58–108  ·  view source on GitHub ↗
(options: UseChatKitOptions)

Source from the content-addressed store, hash-verified

56};
57
58export function useChatKit(options: UseChatKitOptions): UseChatKitReturn {
59 const ref = React.useRef<OpenAIChatKit | null>(null);
60 const stableOptions = useStableOptions(options);
61
62 const methods: ChatKitMethods = React.useMemo(() => {
63 return CHATKIT_METHOD_NAMES.reduce((acc, key) => {
64 acc[key] = (...args: any[]) => {
65 if (!ref.current) {
66 console.warn('ChatKit element is not mounted');
67 return;
68 }
69
70 return (ref.current as any)[key](...args);
71 };
72 return acc;
73 }, {} as ChatKitMethods);
74 }, []);
75
76 const setInstance = React.useCallback(
77 (instance: OpenAIChatKit | null): void => {
78 ref.current = instance;
79 },
80 [],
81 );
82
83 const control: ChatKitControl = React.useMemo(() => {
84 const options = {} as ChatKitOptions;
85 const handlers: ChatKitEventHandlers = {};
86
87 for (const [key, value] of Object.entries(stableOptions)) {
88 if (/^on[A-Z]/.test(key) && key !== 'onClientTool') {
89 // @ts-expect-error - too dynamic for TypeScript
90 handlers[key] = value;
91 } else {
92 // @ts-expect-error - too dynamic for TypeScript
93 options[key] = value;
94 }
95 }
96
97 return {
98 setInstance,
99 options,
100 handlers,
101 };
102 }, [stableOptions, setInstance]);
103
104 return React.useMemo(
105 () => ({ ...methods, control, ref }),
106 [methods, control],
107 );
108}

Callers

nothing calls this directly

Calls 1

useStableOptionsFunction · 0.90

Tested by

no test coverage detected