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?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.