Skip to content

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 (ready Promise for initialization)

Basic Usage (Grouping + Pinning + CRUD)

Live demo of complete history interaction: time grouping, creating, deleting, pinning.

History
Today
Vue 3 Component Development Guide
Optimizing Web Performance
Last 7 Days
Advanced TypeScript Tips
Pinia Best Practices
Last 30 Days
Introl to Vite Plugin Development
Earlier
Micro Frontends Architecture Design
Vue 3 Component Development Guide
Updated: 4/21/2026, 4:31:01 PM
How to encapsulate highly reusable components...
Grouping: Today(2) · Last 7 Days(2) · Last 30 Days(1) · Earlier(1)

IndexedDB Mode (High Volume + Pagination)

Uses storage: 'indexedDB' with pagedConversations to handle large history lists with on-demand lazy loading.

📦 IndexedDB HistoryLoaded 0 / 50

Adapter Comparison

ModeUse CaseCapacitySSR Compat
storage: falseIn-memory, no persistenceUnlimited
storage: 'localStorage' (default)Small history~5MB✅ (Auto skip)
storage: 'indexedDB'High volume + rich dataNo limit✅ (Async init)
storage: CustomAdapterBackend 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

ParamTypeDefaultDescription
initialConversationsAiConversation[][]Initial data (for SSR)
idGenerator() => stringRandom stringCustom ID generation
storagefalse | 'localStorage' | 'indexedDB' | StorageAdapter'localStorage'Persistence adapter
storageKeystring'yh-ui-ai-conversations'Storage key
pageSizenumber20Page size for lazy loading

Returns

FieldTypeDescription
conversationsRef<AiConversation[]>Full history list
groupedConversationsComputed<ConversationGroup[]>Grouped list by time
pagedConversationsComputed<AiConversation[]>Current page data
hasMoreComputed<boolean>If more data exists
loadMore() => Promise<void>Load next page
isLoadingMoreRef<boolean>Loading state
readyPromise<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

Remote Sync

Support syncing with backend API for multi-device data consistency.

ts
import { useAiConversations } from '@yh-ui/hooks'

const remoteSyncAdapter = {
  async fetchConversations() {
    const res = await fetch('/api/conversations')
    return res.json()
  },
  async batchUpdate(conversations) {
    const res = await fetch('/api/conversations/batch', {
      method: 'PUT',
      body: JSON.stringify(conversations)
    })
    return res.json()
  }
}

const { conversations, isSyncing, syncToRemote, startSync, stopSync } = useAiConversations({
  storage: 'localStorage',
  remoteSync: remoteSyncAdapter,
  autoSync: true,
  syncInterval: 30000
})

Remote Sync Options

ParamTypeDefaultDescription
remoteSyncRemoteSyncAdapter-Remote sync adapter
autoSyncbooleanfalseEnable auto sync
syncIntervalnumber30000Sync interval (ms)

Remote Sync Returns

| Field | Type | Description | | ----------------- | --------------------- | --------------------- | ---------- | | isSyncing | Ref<boolean> | Syncing state | | lastSyncTime | Ref<number> | Last sync timestamp | | syncError | Ref<Error | null> | Sync error | | syncToRemote | () => Promise<void> | Manual sync to remote | | fetchFromRemote | () => Promise<void> | Fetch from remote | | startSync | () => void | Start scheduled sync | | stopSync | () => void | Stop scheduled sync |

Remote Sync Notes

  1. autoSync and syncInterval only work when remoteSync is configured
  2. Sync is incremental - local new data will be merged to the list
  3. Recommend calling stopSync when unmounting

Released under the MIT License.