Balius
Balius

Reputation: 69

react-query useQuery typescript No overload matches this call

I'm trying the react query tutorial with typescript, but when fetching data the errors occurred.

code:

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);

this error red unline shows at fetchdata

data:

[
{
"id": 1,
"name": "Batman",
"alterEgo": "Bruce Wayne"
},
{
"id": 2,
"name": "Superman",
"alterEgo": "Clark Kent"
},
{
"id": 3,
"name": "Wonder Woman",
"alterEgo": "Princess Diana"
}
]

error:

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.

I have no idea how to fix it.

resolve:

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

after TkDodo help, add Promise and reture value.

Upvotes: 1

Views: 3923

Answers (1)

TkDodo
TkDodo

Reputation: 29056

axios returns something that is of type AxiosResponse, but you tell react-query that you expect something of type heroType[]. That is not the same. Axios wraps everything into an object that has data and headers and some other options, and only the data is the actual json that is returned from your api. So you need to unwrap it:

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

const { isLoading, data ,error} = useQuery(["heros"], fetchdata);

Also, it's usually better to add type annotations to your fetch function instead of adding generics to useQuery, because it will contain your error to where it actually comes from.

Upvotes: 5

Related Questions