Skip to content

Commit

Permalink
refactor(hooks/xsai): improve structure
Browse files Browse the repository at this point in the history
  • Loading branch information
kwaa committed Jan 30, 2025
1 parent 4bf8b18 commit 3d28f9f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 15 deletions.
43 changes: 29 additions & 14 deletions src/hooks/xsai/_use-fetch-state.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
import { useEffect, useState } from 'react'

/** @internal */
export const useFetchState = <T>(getData: () => Promise<T>, initialState: T) => {
interface GetDataOptions {
abortSignal: AbortSignal
}

/** @internal */
export const useFetchState = <T>(getData: (options: GetDataOptions) => Promise<T>, initialState: T) => {
const [data, setData] = useState<T>(initialState)
const [error, setError] = useState<Error | undefined>()
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<Error | null>(null)

useEffect(() => {
const tryGetData = async () => {
try {
const data = await getData()
setData(data)
}
catch (error) {
setError(error as Error)
}
finally {
setIsLoading(false)
}
const controller = new AbortController()
let isCancelled = false

// eslint-disable-next-line @masknet/no-then
getData({ abortSignal: controller.signal })
.then((data) => {
if (!isCancelled)
setData(data)
})
.catch((error: Error) => {
if (!isCancelled)
setError(error)
})
.finally(() => {
if (!isCancelled)
setIsLoading(false)
})

return () => {
isCancelled = true
controller.abort()
setIsLoading(false)
}
void tryGetData()
}, [getData])

return { data, error, isLoading }
Expand Down
5 changes: 4 additions & 1 deletion src/hooks/xsai/use-list-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { listModels } from '@xsai/model'
import { useFetchState } from './_use-fetch-state'

export const useListModels = (options: ListModelsOptions) => {
const { data, error, isLoading } = useFetchState(async () => listModels(options), [])
const { data, error, isLoading } = useFetchState(async ({ abortSignal }) => listModels({
abortSignal,
...options,
}), [])

return { error, isLoading, models: data }
}

0 comments on commit 3d28f9f

Please sign in to comment.