react-ai-faq-chat
Version:
A smart AI-powered FAQ chatbot
34 lines (33 loc) • 1.27 kB
JavaScript
"use client";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAIFAQChat = useAIFAQChat;
const react_1 = require("react");
function useAIFAQChat(options) {
const [messages, setMessages] = (0, react_1.useState)([]);
const [loading, setLoading] = (0, react_1.useState)(false);
const sendMessage = (0, react_1.useCallback)(async (question) => {
setLoading(true);
setMessages((prev) => [...prev, { text: question, user: true }]);
try {
const res = await fetch(options.apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question }),
});
const { answer } = await res.json();
setMessages((prev) => [...prev, { text: answer, user: false }]);
setLoading(false);
return answer;
}
catch (err) {
setMessages((prev) => [
...prev,
{ text: "Error: Could not reach AI server.", user: false },
]);
setLoading(false);
return "Error: Could not reach AI server.";
}
}, [options.apiUrl]);
return { messages, sendMessage, loading };
}
;