【问题标题】:How to define useAsync (react-async-hook) with TypeScript?如何使用 TypeScript 定义 useAsync (react-async-hook)?
【发布时间】:2022-08-05 12:11:15
【问题描述】:

我正在使用 react-async-hook 来获取 React 组件中的 API 数据。

const popularProducts = useAsync(fetchPopularProducts, []);

fetchPopularProducts() 是使用 fetch 进行 api 调用的异步方法:

export async function fetchPopularProducts(
limit = 10,
start = 1
): Promise<Response<PopularProduct[]>> {
  const apiUrl = `${API_BASE_URL}/rest/V1/fastlaneapi/product/popular? limit=${limit}&start=${start}`;
const res = await fetch(apiUrl);
const json = await res.json();

if (res.status !== 200) {
  const message = json.message !== undefined ? json.message : \"\";
  throw new RequestError(message, res.status);
}

  return json;
}

如何用 TypeScript 定义,useAsync 钩子的响应,我在下面尝试过这样但它不起作用:

  const popularProducts = useAsync<AsyncState<Response<PopularProduct[]>>> 
  (fetchPopularProducts, []);

AsyncState 类型来自 react-async-hook 库,它看起来像这样

export declare type AsyncState<R> = {
  status: AsyncStateStatus;
  loading: boolean;
  error: Error | undefined;
  result: R | undefined;
};

因此,我尝试提供来自 fetchPopularProducts() 方法的结果,而不是 \"R\",它是:Response&lt;PopularProduct[]&gt;,但它不起作用。

错误信息:

TS2769: No overload matches this call.
   Overload 1 of 2, \'(asyncFunction: () => Promise<AsyncState<Response<PopularProduct[]>>>, params: UnknownArgs, options?: Partial<...>): UseAsyncReturn<...>\', gave the following error.
     Argument of type \'(limit?: number, start?: number) => Promise<Response<PopularProduct[]>>\' is not assignable to parameter of type \'() => Promise<AsyncState<Response<PopularProduct[]>>>\'.
       Type \'Promise<Response<PopularProduct[]>>\' is not assignable to type \'Promise<AsyncState<Response<PopularProduct[]>>>\'.
         Type \'Response<PopularProduct[]>\' is missing the following properties from type \'AsyncState<Response<PopularProduct[]>>\': status, loading, error, result
   Overload 2 of 2, \'(asyncFunction: (...args: UnknownArgs) => Promise<AsyncState<Response<PopularProduct[]>>>, params: UnknownArgs, options?: Partial<...>): UseAsyncReturn<...>\', gave the following error.
     Argument of type \'(limit?: number, start?: number) => Promise<Response<PopularProduct[]>>\' is not assignable to parameter of type \'(...args: UnknownArgs) => Promise<AsyncState<Response<PopularProduct[]>>>\'.
       Type \'Promise<Response<PopularProduct[]>>\' is not assignable to type \'Promise<AsyncState<Response<PopularProduct[]>>>\'.

    标签: reactjs typescript react-async


    【解决方案1】:

    我有这个问题好几天了,这对我有用

    1. 使用来自react-async 本身的PromiseFn 类型
    2. 使用对象作为异步函数的参数而不是位置参数

      例子

      使用 1 个参数调用函数

      const { data, error, isPending } = useAsync({
        promiseFn: getActiveSolution,
        slug: '2022-08-04',
      });
      

      用 1 个参数定义函数

      import { useAsync, PromiseFn } from 'react-async';
      
      export const getActiveSolution: PromiseFn<Object> = async ({ slug }) => {
        ...
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-15
      • 2021-03-22
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2017-11-12
      • 2021-05-22
      • 2017-07-13
      相关资源
      最近更新 更多