feat(hooks): add useAgent hook for managing agent state and updates

This commit is contained in:
icarus 2025-09-19 14:07:03 +08:00
parent a424e3a039
commit 14509d1077

View File

@ -0,0 +1,45 @@
import { UpdateAgentForm } from '@renderer/types'
import { formatErrorMessageWithPrefix } from '@renderer/utils/error'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import useSWR from 'swr'
import { useAgentClient } from './useAgentClient'
export const useAgent = (id: string | null) => {
const { t } = useTranslation()
const client = useAgentClient()
const key = client.agentPaths.base
const fetcher = useCallback(async () => {
if (id === null) {
return null
}
const result = await client.getAgent(id)
return result
}, [client, id])
const { data, error, isLoading, mutate } = useSWR(key, fetcher)
const updateAgent = useCallback(
async (form: UpdateAgentForm) => {
try {
// may change to optimistic update
const result = await client.updateAgent(form)
mutate((prev) => ({
...prev,
...result
}))
window.toast.success(t('common.update_success'))
} catch (error) {
window.toast.error(formatErrorMessageWithPrefix(error, t('agent.update.error.failed')))
}
},
[client, mutate, t]
)
return {
agent: data,
error,
isLoading,
updateAgent
}
}