TanStackT
TanStack14mo ago
6 replies
brilliant-orange

Retrieving query data without passing the whole queryKey

Hi all,

I have a small custom query:
const fetchData = async (params?: IParams): Promise<Data> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve({ value: ['1'], status: 'success' }), 2000)
  })
}

interface Data {
  value: string[],
  status: string
}

interface IParams {
  id: string,
  name: string,
  value: number,
  meta: string,
}

const queryKey = 'queryKey12345';
const useData = (params?: IParams) => {
  return useQuery({
    queryKey: [queryKey, params],
    queryFn: () => fetchData(params),
    enabled: false
  })
}


In some components I have no 'params', so I want to retrieve the data like this:
const {data} = useData();


Unfotrunately, I'm getting indefined as a data, because I did not pass the params.

I've found only one dirty trick to fix it - do not pass the 'params' to queryKey array:
const useData = (params?: IParams) => {
return useQuery({
// eslint-disable-next-lone @tanstack/query/exhaustive-deps
queryKey: [queryKey],
queryFn: () => fetchData(params),
enabled: false
})
}

Is that a 'go-to'?
Was this page helpful?