#extract generic types from react-query QueryOptions

2 messages · Page 1 of 1 (latest)

nocturne plaza
#

I came up with the following which works but i'd like to alter the generics a bit

import { type QueryOptions, useMutation, useQueryClient } from "@tanstack/react-query"

export function useImperativeQuery<D = unknown, E = unknown>() {
  const queryClient = useQueryClient()
  const { mutate, ...mutation } = useMutation({
    mutationFn: async (queryOptions: QueryOptions<D, E>) => await queryClient.fetchQuery(queryOptions),
  })
  return {
    ...mutation,
    load: mutate,
  }
}

I'm using functions to generate the queryOptions. Example:

const foobarsQuery = () => ({
  queryKey: ['data'],
  queryFn: () => Promise.resolve([{id: 1, name: 'Foobar'}])
})

I'd like to alter the useImperativeQuery generic to accept the query option function type and infer the data from it. Example

const query = useImperativeQuery<typeof foobarsQuery>()

How do?

https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wChRJY4BvOAVwGckBZOmFGYCAOwBp6mARTpIoATwDCAG2BJuMfjDFgkcYaLEB5MJx4M4AXzjZcBAALtuDdmgDWAeiLoYAWgCOI8WQrR4AL2McPHw-CAATMlI0PXgGNAALJBAUOABeOD8AOggAIwArJAwACmpSODgVCDApJAAuDMyUKCgUMSKs3ILi0vLy4DD6rOsoYG4AcyKASl4y3u4UEDqG4dGJ6dnygDcUKRFBzJXxqdmDScnSU9JSJRU4ABEOFPSs0cxRAB4bpAhMODjE5IAPiumDo3AwXG4AiQAElwKIOMBNkh1OJ3nc0vRuLZuBAAO58OAAUUxYJx+O4gKmNFm0Ss8A8GmksnkpKEnkkMjkMGO5Tp1hocBAbA4SH4mQlwvYuihRnSjBYIplJQ2QqVkIAYtx6igGGJwXAiozxNoZQx6qitDpIQx0fwiYDJmlAXAUHiUMAGRzmdzMm8YAlLUaOaabedypdykQYHQoFCer0JZkpYieDNenApBAUAM1dKxScLlckAAPShYMEQnjEksLapIADKSBqxTAODA5sQxBgmQkuEg3G5AAV2wwAOqe+IQNjITDvfBMFswfCOml8mJwY1iNmw+EtTjIy3ox5U860jc8Zl2THU1IuhPlLeZLM5lUZrcAaSQYnqAG18GEjz4AAuumvRblqOp6gat73qq670nARD6OkboelgSABvERT4PEMAwGAtT2PYYS4B63CZNEID2CgYDAPYlT1vg4YZnA-LwHkDDVqh7qekhSAMJknE8Mc8H8TGcZ-AkSQoJkYBNEwRTCdwLERicLEGFcUaYbGUJFKq7yLoU8DUEmbZVAwRiXjIdipNQ1nAHYBjAqxNDBhomSAewAD8cnfPWcDed5cC-sBkzJrRRRVDKzqGmJ5TvNFkJwLY352UlPCZNsuxIM59nWpl2UiAY7z2BllJiWcmkZqVRkYC5cDnJppBAA

dreamy tundraBOT
#

@nocturne plaza Here's a shortened URL of your playground link! You can remove the full link from your message.

dadamssg#0

Preview:```ts
import React from "react"
import {
useMutation,
useQueryClient,
type QueryOptions,
} from "@tanstack/react-query"
import z from "zod"

const schema = z.object({
people: z.array(
z.object({
id: z.string(),
name: z.string(),
value: z.string(),
})
),
...```