useAiConversations Session History Management 💾
Dedicated Hook for managing the session list in the sidebar, featuring:
- 📁 Pluggable Persistence (localStorage / IndexedDB / Custom Adapter)
- 🗂️ Automatic Time Grouping (Today / Last 7 Days / Last 30 Days / Earlier)
- 📌 Pinning Operations
- ♾️ Pagination & Lazy Loading
- 🌐 SSR Friendly (
readyPromise for initialization)
Basic Usage (Grouping + Pinning + CRUD)
Live demo of complete history interaction: time grouping, creating, deleting, pinning.
IndexedDB Mode (High Volume + Pagination)
Uses IndexedDBAdapter to handle extremely large records with on-demand lazy loading.
Adapter Comparison
| Mode | Use Case | Capacity | SSR Compat |
|---|---|---|---|
storage: false | In-memory, no persistence | Unlimited | ✅ |
storage: 'localStorage' (default) | Small history | ~5MB | ✅ (Auto skip) |
storage: 'indexedDB' | High volume + rich data | No limit | ✅ (Async init) |
storage: CustomAdapter | Backend API | — | ✅ |
Custom Adapter (Backend API)
ts
import { useAiConversations, type StorageAdapter } from '@yh-ui/hooks'
const apiAdapter: StorageAdapter = {
getItem: async (key) => {
const res = await fetch(`/api/user/conversations?key=${key}`)
return res.ok ? res.text() : null
},
setItem: async (key, value) => {
await fetch('/api/user/conversations', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value })
})
},
removeItem: async (key) => {
await fetch(`/api/user/conversations?key=${key}`, { method: 'DELETE' })
}
}
const { conversations } = useAiConversations({ storage: apiAdapter })API
Options
| Param | Type | Default | Description |
|---|---|---|---|
initialConversations | AiConversation[] | [] | Initial data (for SSR) |
idGenerator | () => string | Random string | Custom ID generation |
storage | false | 'localStorage' | 'indexedDB' | StorageAdapter | 'localStorage' | Persistence adapter |
storageKey | string | 'yh-ui-ai-conversations' | Storage key |
pageSize | number | 20 | Page size for lazy loading |
Returns
| Field | Type | Description |
|---|---|---|
conversations | Ref<AiConversation[]> | Full history list |
groupedConversations | Computed<ConversationGroup[]> | Grouped list by time |
pagedConversations | Computed<AiConversation[]> | Current page data |
hasMore | Computed<boolean> | If more data exists |
loadMore | () => Promise<void> | Load next page |
isLoadingMore | Ref<boolean> | Loading state |
ready | Promise<void> | Initialization finished (SSR await) |
createConversation | (title, meta?) => Promise<AiConversation> | Create history |
removeConversation | (id) => Promise<void> | Delete history |
updateConversation | (id, updates) => Promise<void> | Update history |
pinConversation | (id, pinned?) => Promise<void> | Toggle pinning |
clear | () => Promise<void> | Clear all |