sairaj
sairaj

Reputation: 413

how to satisfy typescript in query function of react-querie's useQuery hook

I am using useQuery hook from react-query and when I try to access my keys inside of query-function i.e., 2nd argument for useQuery, I am facing an issue with typescript it's complaining on this statement

const postId = queryKey[1].id as any

that

Property 'id' does not exist on type 'string | { id: string | undefined; comments: boolean; }'.
  Property 'id' does not exist on type 'string'.ts(2339)

Everything works fine, I have a defined in postId, the request is sent to the server and I get a response back, problem is with typescript, I even tried to assert the type but doesn't work

  const { data } = useQuery(['post', { id: post?.id, comments: true }], async ({ queryKey }) => {
    const postId = queryKey[1].id as any
     const { data } = await axios.get(`/post/${postId}`, {
       headers: {
         Authorization: `Bearer ${user?.idToken}`,
       },
     })
     return data
  })

Is there any typescript way to solve this ?

Upvotes: 3

Views: 2234

Answers (1)

TkDodo
TkDodo

Reputation: 28733

Types of the queryKey flow through very well in react-query, but you have to give your key an explicit type. If you just do:

['post', { id: post?.id, comments: true }]

Typescript will try to infer the best possible thing, which is an Array of string or object. Every position can have a string or an object as far as Typescript is concerned, so you can’t access the second element like that. You need to give your key a more concrete type. The easiest way is to use const assertions:

['post', { id: post?.id, comments: true }] as const

With that, typescript will infer a readonly Tulpe where the first Element is a string and the second element is an object. With that, your access should work just fine.

Upvotes: 2

Related Questions