4

I'm using react query with typescript. What is the type of the arguments given to the function?

export const useIsTokenValid = () => { const { data: token } = useQuery<string | null>(['token'], getToken, { refetchOnMount: false, }); return useQuery(['isTokenValid', token], validateToken, { refetchOnMount: false, enabled: typeof token !== 'undefined', }); };

export const validateToken = async ({ queryKey }: WHAT_TYPE_SHOULD_I_PUT_HERE) => {
  console.log('validating token');
  const [_, token] = queryKey;
  if (token) {
    const res = await axios.get<boolean>(BACKEND_URL + '/', {
      headers: {
        Authorization: token,
      },
    });
    return res.data;
  } else {
    return false;
  }
};

What type should I put where there is "WHAT_TYPE_SHOULD_I_PUT_HERE"?

Edit: As suggested, I gave the type

QueryFunction<
  boolean,
  [string, string | null | undefined]
>

to the function. I don't get errors anymore on the function, but I get errors on the useQuery where I call that function, even though the types are correct (I think).

Theese are the errors:

(alias) const validateToken: QueryFunction<boolean, [string, string | null | undefined]> import validateToken No overload matches this call. Overload 1 of 9, '(queryKey: QueryKey, queryFn: QueryFunction<boolean, QueryKey>, options?: (Omit<UseQueryOptions<boolean, unknown, boolean, QueryKey>, "queryKey" | ... 1 more ... | "queryFn"> & { ...; }) | undefined): UseQueryResult<...>', gave the following error. Argument of type 'QueryFunction<boolean, [string, string | null | undefined]>' is not assignable to parameter of type 'QueryFunction<boolean, QueryKey>'. The type 'QueryKey' is 'readonly' and cannot be assigned to the mutable type '[string, string | null | undefined]'. Overload 2 of 9, '(queryKey: QueryKey, queryFn: QueryFunction<boolean, QueryKey>, options?: (Omit<UseQueryOptions<boolean, unknown, boolean, QueryKey>, "queryKey" | ... 1 more ... | "queryFn"> & { ...; }) | undefined): DefinedUseQueryResult<...>', gave the following error. Argument of type 'QueryFunction<boolean, [string, string | null | undefined]>' is not assignable to parameter of type 'QueryFunction<boolean, QueryKey>'. Overload 3 of 9, '(queryKey: QueryKey, queryFn: QueryFunction<boolean, QueryKey>, options?: Omit<UseQueryOptions<boolean, unknown, boolean, QueryKey>, "queryKey" | "queryFn"> | undefined): UseQueryResult<...>', gave the following error. Argument of type 'QueryFunction<boolean, [string, string | null | undefined]>' is not assignable to parameter of type 'QueryFunction<boolean, QueryKey>'.ts(2769)

2 Answers 2

12

The type you are looking for is QueryFunctionContext, and it's exported from react-query:

import { QueryFunctionContext } from '@tanstack/react-query';
export const validateToken = async ({ queryKey }: QueryFunctionContext<[string, string | null | undefined]>) => {

You can see a working version in this typescript playground

Sign up to request clarification or add additional context in comments.

2 Comments

How this is different from my answer? QueryFunction gives you the same argument type and also allows you to specify return value
Both answers "work". OP asked for how to type the parameter passed to queryFunction (the queryFunctionContext), not the whole query function itself. If you get type inference or don't have easy access to the return type of the function that makes the request, just typing the context is what you want. You can also just inline the whole query function and then you don't need to specify any types, but again, that wasn't the question.
8

You should use QueryFunction type from the library:

import { QueryFunction } from "@tanstack/react-query";

export const validateToken: QueryFunction<number | undefined, [string, string]> = async ({queryKey}) => {
  // ...
};

First generic type of QueryFunction is your return data type, and second one should describe the queryKey, in this case you have ['userId', token] which is basically [string, string]

6 Comments

I get no more errors on the function, but now in the useQuery where I am using that function I get an error (check the edited question)
Why you gave it type boolean instead of number | undefined? Here is working example on Codesandbox, codesandbox.io/s/… make sure you don't such simple typos like boolean instead of number and etc
because that query returns a boolean
useQuery<boolean>(['isTokenValid', token], validateToken);
It's not, you specified number manually here axios.get<number | undefined> and in the other if branch you return undefined, so it can't possibly return boolean. You also specified number type here useQuery<number | undefined>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.