From 6641abe8d2c18a82b0bef375199b2997326c9020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=97=8D+85CD?= <50108258+kwaa@users.noreply.github.com> Date: Thu, 30 Jan 2025 15:15:58 +0800 Subject: [PATCH] refactor(hooks/xsai): use foxact/use-abortable-effect --- src/hooks/xsai/_use-fetch-state.ts | 29 ++++++++--------------------- src/hooks/xsai/use-list-models.ts | 2 +- 2 files changed, 9 insertions(+), 22 deletions(-) diff --git a/src/hooks/xsai/_use-fetch-state.ts b/src/hooks/xsai/_use-fetch-state.ts index 255097c..bd7de73 100644 --- a/src/hooks/xsai/_use-fetch-state.ts +++ b/src/hooks/xsai/_use-fetch-state.ts @@ -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 = (getData: (options: GetDataOptions) => Promise, initialState: T) => { +export const useFetchState = (getData: (signal: AbortSignal) => Promise, initialState: T) => { const [data, setData] = useState(initialState) const [error, setError] = useState() 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 } diff --git a/src/hooks/xsai/use-list-models.ts b/src/hooks/xsai/use-list-models.ts index 2c6ba07..04082da 100644 --- a/src/hooks/xsai/use-list-models.ts +++ b/src/hooks/xsai/use-list-models.ts @@ -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, }), [])