lukemorales / query-key-factory

A library for creating typesafe standardized query keys, useful for cache management in @tanstack/query
https://www.npmjs.com/package/@lukemorales/query-key-factory
MIT License
1.18k stars 32 forks source link

Allow all query options within query definition (i.e. besides just queryKey, queryFn) #36

Closed codebycarlos closed 1 year ago

codebycarlos commented 1 year ago

What do you think about allowing all useQuery options, in order to allow more complex definitions?

For instance, if we wanted to always run this detail query with refetchOnMount set to 'always':

  export const users = createQueryKeys('users', {
    detail: (userId: string) => ({
      queryKey: [userId],
      queryFn: () => api.getUser(userId),
    }),
  });

to

  export const users = createQueryKeys('users', {
    detail: (userId: string) => ({
      queryKey: [userId],
      queryFn: () => api.getUser(userId),
      refetchOnMount: 'always', // add refetchOnMount set to 'always'
      ...more useQuery options here...
    }),
  });

And so on..

codebycarlos commented 1 year ago

Also, thanks for this library, I think it's definitely a step in the right direction towards solving the mess that it can be managing queries and keys 🙂

lukemorales commented 1 year ago

Thanks for the great ideas @codebycarlos.

The suggestion is pretty good, but I need to sleep on the idea a little bit. It would be great to have all the query set up in there, but I'm not sure it introduces responsibilities beyond to what was intended for this lib. If we get to the point of having all of this inside the lib, we might as well just return custom hooks? Feels like a natural path, but then there's already react-query-kit as a solution for that...

panukettu commented 11 months ago

+1

Stumbled across this lib recently and refactored one project to use it. I did define all my queries thinking this was possible:

export const getSomeQueryDefinition = (filters: BaseFilter = filter.base()) => ({
  queryKey: [{ filters }] as const,
  queryFn: () => fetchSomeData(filters),
  options: {
      enabled: !!filters.foo && someComplexCheck(filters.bar),
      staleTime: 8000,
  },
})

...

export const queries = createQueryKeyStore({
  foo: { 
    myQuery: getSomeQueryDefinition,
  }
})

anyways thanks for making this lib 👍🏻