Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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👍')
     }
 };
like image 720
Naveed Ali Rehmani Avatar asked Oct 24 '25 15:10

Naveed Ali Rehmani


1 Answers

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>

like image 192
Kostiantyn Ko Avatar answered Oct 27 '25 04:10

Kostiantyn Ko