embedia
Version:
Zero-configuration AI chatbot integration CLI - direct file copy with embedded API keys
58 lines (47 loc) • 1.68 kB
text/typescript
'use client';
import { useState, useCallback } from 'react';
import type { Message } from './types';
export const useChat = () => {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setInput(e.target.value);
};
const handleSubmit = useCallback(async (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim()) return;
const userMessage: Message = { role: 'user', content: input };
setMessages((prev) => [...prev, userMessage]);
setInput('');
setIsLoading(true);
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
history: [...messages, userMessage],
}),
});
if (!response.ok) {
throw new Error('API response was not ok.');
}
const data = await response.json();
const assistantMessage: Message = { role: 'assistant', content: data.response };
setMessages((prev) => [...prev, assistantMessage]);
} catch (error) {
console.error('Failed to fetch chat response:', error);
const errorMessage: Message = { role: 'assistant', content: "Sorry, I'm having trouble connecting. Please try again later." };
setMessages((prev) => [...prev, errorMessage]);
} finally {
setIsLoading(false);
}
}, [input, messages]);
return {
messages,
input,
handleInputChange,
handleSubmit,
isLoading,
};
};