react-query useQuery typescript 没有重载与此调用匹配

Bal*_*ius 1 typescript reactjs react-query

我正在尝试使用打字稿进行反应查询教程,但是在获取数据时发生了错误。

代码:

type heroType = {
  id: number;
  name: string;
  alterEgo: string;
};

function QueryDataFetch() {
  const fetchdata = ()=>{ return axios.get("http://localhost:8000/superheroes")}
  const { isLoading, data ,error} = useQuery<heroType[]>(["heros"],fetchdata);
Run Code Online (Sandbox Code Playgroud)

此错误红色 unline 显示在fetchdata

数据:

[
{
"id": 1,
"name": "Batman",
"alterEgo": "Bruce Wayne"
},
{
"id": 2,
"name": "Superman",
"alterEgo": "Clark Kent"
},
{
"id": 3,
"name": "Wonder Woman",
"alterEgo": "Princess Diana"
}
]
Run Code Online (Sandbox Code Playgroud)

错误:

TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '() => Promise<AxiosResponse<any, any>>' is not assignable to parameter of type 'QueryFunction<heroType[], QueryKey>'.
Failed to compile.
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决它。

解决:

  const fetchdata = async (): Promise<heroType[]> => {
    const payload = await axios
      .get("http://localhost:8000/superheroes")
      .then((res) => {
        return res.data;
      });
    return payload;
  };
Run Code Online (Sandbox Code Playgroud)

在 TkDodo 帮助之后,添加 Promise 和 return 值。

TkD*_*odo 5

axios 返回类型为 的内容AxiosResponse,但您告诉react-query您期望类型为 的内容heroType[]。那不一样。 Axios 将所有内容包装到一个对象中,该对象具有dataheaders以及其他一些选项,并且只有 是data从 api 返回的实际 json。所以你需要解开它:

const fetchdata = async (): Promise<heroType[]> => {
  const response = await axios.get("http://localhost:8000/superheroes")}
  return response.data
}

const { isLoading, data ,error} = useQuery(["heros"], fetchdata);
Run Code Online (Sandbox Code Playgroud)

此外,通常最好向 fetch 函数添加类型注释,而不是向 useQuery 添加泛型,因为它将包含错误的实际来源。