| import { useEffect } from "react"; |
| import { useHistoryStore, type HistoryItem } from "../store/useAppStore"; |
| import { API_BASE } from "../api/client"; |
|
|
| export async function saveSessionToBackend( |
| userId: string, |
| item: HistoryItem, |
| ): Promise<void> { |
| try { |
| await fetch(`${API_BASE}/api/sessions/${userId}`, { |
| method: "POST", |
| headers: { "Content-Type": "application/json" }, |
| body: JSON.stringify(item), |
| }); |
| } catch { |
| |
| } |
| } |
|
|
| export async function deleteSessionFromBackend( |
| userId: string, |
| filename: string, |
| ): Promise<void> { |
| try { |
| await fetch( |
| `${API_BASE}/api/sessions/${userId}/${encodeURIComponent(filename)}`, |
| { method: "DELETE" }, |
| ); |
| } catch { |
| |
| } |
| } |
|
|
| export function useLoadSessionHistory(): void { |
| const userId = useHistoryStore((s) => s.userId); |
| const localHistory = useHistoryStore((s) => s.sessionHistory); |
| const setSessionHistory = useHistoryStore((s) => s.setSessionHistory); |
|
|
| useEffect(() => { |
| async function load() { |
| try { |
| const res = await fetch(`${API_BASE}/api/sessions/${userId}`); |
| if (!res.ok) return; |
| const data = await res.json(); |
| const remote: HistoryItem[] = data.items ?? []; |
| if (remote.length === 0) return; |
|
|
| |
| const merged = [...remote, ...localHistory]; |
| const seen = new Set<string>(); |
| const deduped = merged.filter((item) => { |
| if (seen.has(item.filename)) return false; |
| seen.add(item.filename); |
| return true; |
| }); |
| deduped.sort((a, b) => b.uploadedAt - a.uploadedAt); |
| setSessionHistory(deduped.slice(0, 10)); |
| } catch { |
| |
| } |
| } |
| load(); |
| |
| }, [userId]); |
| } |
|
|