【问题标题】:I am trying to work with useQuery in Typescript我正在尝试在 Typescript 中使用 useQuery
【发布时间】:2021-11-17 16:03:12
【问题描述】:

在 typescript/react 中使用 useQuery 挂钩时,我收到一条错误消息,指出 Argument of type '(param: Param) => Promise<any>' 不可分配给 'QueryFunction<IResponsePlanets, QueryKey>' 类型的参数。

但请记住,onSuccess 函数在这里起作用。即使我得到一个错误

这是参数的接口

type Param = {
    pageParam?: undefined;
    queryKey: [string, { page: number }];
}

这是异步函数

const fetchFunction = async (param: Param) => {
    const [key, { page }] = param.queryKey;
    const response = await fetch(`https://swapi.dev/api/planet/?page=${page}`);
    return response.json();
};

这是 useQuery 钩子

 const { status, error, data } = useQuery<IResponsePlanets, Error>(["planets", { page: 1 }], fetchFunction, {
     staleTime: 5000,
     onSuccess: () => {
         console.log('working????')
     }
 };

【问题讨论】:

  • 请提供复制品(例如codesandbox),否则很难说

标签: reactjs typescript react-query


【解决方案1】:

问题在于你的fetchFunction签名

const fetchFunction = async (param: Param) => {
                                    ^^^^^
    const [key, { page }] = param.queryKey;
    const response = await fetch(`https://swapi.dev/api/planet/?page=${page}`);
    return response.json();
};

参数的类型应该是QueryFunctionContext&lt;Param&gt;

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2018-11-15
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多