Skip to content
Latestv1.0.30

useAiPersistence Conversation Persistence Hook

Basic Usage

The useAiPersistence hook provides conversation history persistence based on IndexedDB.

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

const {
  conversations,
  currentConversationId,
  createConversation,
  addMessage
  // ...
} = useAiPersistence()

API

Options

PropertyDescriptionTypeDefault
storageCustom storage adapterStorageAdapternew IndexedDBAdapter()
conversationKeyPersistent storage keystring'ai-conversations'
autoSaveSave automatically on changebooleantrue

Return Value

PropertyDescriptionType
conversationsList of all conversationsRef<Conversation[]>
currentConversationIdCurrent conversation IDRef<string | null>
isLoadingWhether loadingRef<boolean>
isSavingWhether savingRef<boolean>
errorError messageRef<Error | null>

Methods

Method NameDescriptionParameters
loadConversationsLoad conversations() => Promise<void>
saveConversationsSave conversations() => Promise<void>
createConversationCreate new conversation(title?: string) => Conversation
deleteConversationDelete conversation(id: string) => void
getCurrentConversationGet current conversation() => Conversation | undefined
addMessageAdd message(message: Omit<ConversationMessage, 'id' | 'timestamp'>) => ConversationMessage | undefined
updateMessageUpdate message(messageId: string, updates: Partial<ConversationMessage>) => void
clearCurrentConversationClear current conversation() => void
exportConversationsExport conversations() => string
importConversationsImport conversations(json: string) => Promise<boolean>
setCurrentConversationSet current conversation(id: string) => void

Type Definitions

Conversation

ts
interface Conversation {
  id: string
  title: string
  messages: ConversationMessage[]
  createdAt: number
  updatedAt: number
}

ConversationMessage

ts
interface ConversationMessage {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: number
  metadata?: Record<string, any>
}

Storage Adapters

Using Custom Storage

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

const apiClient = new APIClient('https://api.example.com', {
  Authorization: 'Bearer token'
})

const { conversations } = useAiPersistence({
  storage: apiClient,
  conversationKey: 'my-conversations'
})

IndexedDBAdapter

Uses IndexedDB storage by default, suitable for browser environments.

APIClient

Configurable backend API client with reserved interfaces for enterprise backend services.

Released under the MIT License.