lukemorales / query-key-factory

A library for creating typesafe standardized query keys, useful for cache management in @tanstack/query

Home Page:https://www.npmjs.com/package/@lukemorales/query-key-factory

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Create inferQueryFactory type

joaom00 opened this issue · comments

First, nice work with this library!

I think this library could provide a little helper to get the type of the queryKey passed to the queryFn, do you think that makes sense?

The helper would look like this:

import { useQuery, QueryFunctionContext } from '@tanstack/react-query'
import { createQueryKeys, inferQueryFactory } from "@lukemorales/query-key-factory"

export const productsKeys = createQueryKeys('products', {
  bestSelling: null,
  search: (query: string, limit = 15) => ({ query, limit }),
  byId: (productId: string) => ({ productId }),
});

type ProductKeys = inferQueryFactory<typeof productsKeys>

const fetchTodos = (context: QueryFunctionContext<ProductKeys['byId']>) => {
  const queryKey = context.queryKey // readonly ['products', 'byId', { productId: string }]

  // fetch todos...
}

useQuery(productsKeys.byId('product-id'), fetchTodos)

That's a great idea @joaom00, feel free to open a PR adding this type

Nice that you liked it!

Is the name inferQueryFactory ok? Or do you have another suggestion?

inferQueryFactory has a good sound to it, but perhaps inferQueryKeys is more aligned with createQueryKeys