Fix AI chat: handle undefined sessions
- Add error state to display API errors - Safe guard sessions.map with (sessions || []) - Show error message on API failure Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
fb2527f4b3
commit
881888ef10
1 changed files with 13 additions and 1 deletions
|
|
@ -25,6 +25,7 @@ export default function AIChatPage() {
|
||||||
const [input, setInput] = useState("");
|
const [input, setInput] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [sidebarOpen, setSidebarOpen] = useState(true);
|
const [sidebarOpen, setSidebarOpen] = useState(true);
|
||||||
|
const [error, setError] = useState<string>("");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (childId) {
|
if (childId) {
|
||||||
|
|
@ -37,7 +38,13 @@ export default function AIChatPage() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/chat?childId=${childId}`);
|
const res = await fetch(`/api/chat?childId=${childId}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
if (data.error) {
|
||||||
|
setError(data.error);
|
||||||
|
console.error("API error:", data.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
setSessions(data.sessions || []);
|
setSessions(data.sessions || []);
|
||||||
|
setError("");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to fetch:", err);
|
console.error("Failed to fetch:", err);
|
||||||
}
|
}
|
||||||
|
|
@ -113,6 +120,11 @@ export default function AIChatPage() {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen bg-gradient-to-br from-rose-50 to-amber-50">
|
<div className="flex h-screen bg-gradient-to-br from-rose-50 to-amber-50">
|
||||||
|
{error && (
|
||||||
|
<div className="p-4 bg-red-100 text-red-700">
|
||||||
|
Error: {error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{/* Sidebar */}
|
{/* Sidebar */}
|
||||||
<div className={`${sidebarOpen ? "w-64" : "w-0"} overflow-hidden transition-all`}>
|
<div className={`${sidebarOpen ? "w-64" : "w-0"} overflow-hidden transition-all`}>
|
||||||
<div className="w-64 p-4 border-r bg-white h-full overflow-y-auto">
|
<div className="w-64 p-4 border-r bg-white h-full overflow-y-auto">
|
||||||
|
|
@ -121,7 +133,7 @@ export default function AIChatPage() {
|
||||||
<button onClick={createNewSession} className="text-rose-400">+</button>
|
<button onClick={createNewSession} className="text-rose-400">+</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{sessions.map(session => (
|
{(sessions || []).map(session => (
|
||||||
<div
|
<div
|
||||||
key={session.id}
|
key={session.id}
|
||||||
onClick={() => setCurrentSessionId(session.id)}
|
onClick={() => setCurrentSessionId(session.id)}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue