Skip to content

Commit

Permalink
refactor(hooks/xsai): use foxact/use-abortable-effect
Browse files Browse the repository at this point in the history
kwaa committed Jan 30, 2025
1 parent 3ec086c commit 6641abe
Showing 2 changed files with 9 additions and 22 deletions.
29 changes: 8 additions & 21 deletions src/hooks/xsai/_use-fetch-state.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,27 @@
import { useEffect, useState } from 'react'
import { useAbortableEffect } from 'foxact/use-abortable-effect'
import { useState } from 'react'

/** @internal */
interface GetDataOptions {
abortSignal: AbortSignal
}

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

useEffect(() => {
const controller = new AbortController()
let isCancelled = false

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

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

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

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

0 comments on commit 6641abe

Please sign in to comment.