Naveed Ali Rehmani
Naveed Ali Rehmani

Reputation: 59

I am trying to work with useQuery in Typescript

When working with the useQuery hook in typescript/react I get an error saying Argument of type '(param: Param) => Promise<any>' is not assignable to parameter of type 'QueryFunction<IResponsePlanets, QueryKey>'.

but keep in mind that onSuccess function is working here. even though I get an error

This is the interface for params

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

This is the async function

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

This is the useQuery hook

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

Upvotes: 4

Views: 6245

Answers (1)

Kostiantyn Ko
Kostiantyn Ko

Reputation: 2736

The problem is in signature of your 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();
};

The argument should be of type QueryFunctionContext<Param>

Upvotes: 2

Related Questions