TanStackT
TanStack16mo ago
16 replies
slow-yellow

QueryOptions as generic prop

Im implementing a Link component with a prefetch prop, Whenever someone hovers a link and it has the prefetch prop i want to call queryClient.prefetchQuery(props.prefetch)
My problem is to properly implement the prop type via typescript.
I have some queries set up via queryOptions like so
export const authQueries = {
  getMe: () =>
    queryOptions({
      queryKey: ['getMe'],
      queryFn: async ({ signal }) => {
        const { data } = await authService.getMe({
          signal
        })
        return data
      },
    })
}


Now in my Link component it looks like this
<script lang="ts" setup>
import { useQueryClient, type UseQueriesOptions } from '@tanstack/vue-query'
import type { RouteLocationRaw } from 'vue-router'

const props = defineProps<{
    to: RouteLocationRaw
    prefetch?: any
  }>()


const queryClient = useQueryClient()
const prefetch = () => {
  if (!props.prefetch) return
  queryClient.prefetchQuery(props.prefetch)
}
</script>
<template>
  <RouterLink :to custom v-slot="{ isExactActive, href, navigate }">
    <a :href="href" @mouseover="prefetch" @focus="prefetch" @click="navigate"
      <slot></slot>
    </a>
  </RouterLink>
</template>

And this is how i want to use it
<script setup lang="ts">
import { authQueries } from '@/queries/auth'

import Link from '@/components/navigation/Link.vue'

const prefetch = authQueries.getMe()
</script>

<template>
  <nav>
    <Link :to="{ name: 'dashboard' }" :prefetch="prefetch"
      >Dashboard</Link
    >
</template>


This works perfectly, But how can i set the prefetch prop in Link to its correct type?
PrefetchQuery expects the type FetchQueryOptions but it has four generics i dont know how to type.

Repro: https://codesandbox.io/p/live/2835ffbd-85f5-4048-8035-c307b7516032
Was this page helpful?