mirror of
https://github.com/CherryHQ/cherry-studio.git
synced 2025-12-27 12:51:26 +08:00
feat(hooks): add useAgent hook for managing agent state and updates
This commit is contained in:
parent
a424e3a039
commit
14509d1077
45
src/renderer/src/hooks/agents/useAgent.ts
Normal file
45
src/renderer/src/hooks/agents/useAgent.ts
Normal 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
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user