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.16k stars 32 forks source link

Typing: staleTime not available as prop in static query #83

Open Dammic opened 7 months ago

Dammic commented 7 months ago

Hello!

I ran into a small issue when trying to use the library. It seems that the staleTime is not available in types when using a static query without any queryKey, while it works just fine when the query is dynamic:

Screenshot 2024-01-18 at 13 18 01 Screenshot 2024-01-18 at 13 18 38

Is this behaviour intended? I would assume the props should be similar in both cases. Thanks in advance for reply!

gomesalexandre commented 7 months ago

@Dammic not sure if you've figured this out by now, but the typings are misleading either way - helper functions of createQueryKeys only return queryFn and queryKey. All other react-query useQuery options you may pass (staleTime, gcTime etc) will be ommitted.

This can be seen in the implementation:

https://github.com/lukemorales/query-key-factory/blob/e110092b6c736494483b5c1326a316f702fdeb92/src/create-query-keys.ts#L55-L58

@lukemorales I think this behavior should be documented, or support added for all other useQuery() options being passed through, as current typings wrongly indicate this is supported and one may lose a bit of sanity trying to figure out why e.g queries aren't always getting fresh data when using {gcTime: 0, staleTime: 0}

lukemorales commented 7 months ago

@gomesalexandre the behavior is documented, there are no examples with options other than queryKey and queryFn, and nowhere in the documentation it is told that every query option is supported, every attempt of using anything else other than queryKey and queryFn it's the user to blame. With that said, the issue is that typescript widens the type of the object as long as some of them match the expected format (with queryKey and/or queryFn) and it allows extra keys not defined before. But I'm already working on a rewrite of the lib to allow all queryOptions to be defined and problems like this will not happen again

lukemorales commented 7 months ago

While the major version is still not out there, I released v1.1.3 that makes the object returned in a dynamic query super strict to the only expected keys. Hope that prevents any future confusion

gomesalexandre commented 7 months ago

That was super fast @lukemorales, thank you! 👑