Skip to content

queryKeyHashFn() overwrites all other useQuery() calls #6237

Closed as not planned

Description

@zirkelc

Describe the bug

When setting the queryKeyHashFn() as option on one useQuery(), it seems to apply to all other useQuery() calls as well:

  const userQuery = useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const { data } = await axios.get(
        'https://jsonplaceholder.typicode.com/users',
      )
      return data
    },
    queryKeyHashFn: (input) => {
      console.log("queryKeyHashFn", input);
      return JSON.stringify(input);
    },
  });

It prints to the console for the query key['post', 1] even though it was only defined on the query key ['users']:

image

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/github/tanstack/query/tree/main/examples/react/basic?embed=1

Steps to reproduce

  1. Call multiple different useQuery
  2. Set queryKeyHashFn on just one useQuery in the middle
  3. Print the input which contains the query key to the console

Expected behavior

I expected to see only calls to queryKeyHashFn for the useQuery on which is was defined

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

  • OS: macOS 12.1
  • Browser: Chrome 118

Tanstack Query adapter

React

TanStack Query version

4.0.0, 5.0.0

TypeScript version

No response

Additional context

No response

Activity

  1. TkDodo commented on Oct 30, 2023

    @TkDodo
    Collaborator

    That's a tricky situation. Here's what's happening:

    • the example calls queryClient.getQueryData against all keys:
      style={
      // We can access the query data here to show bold links for
      // ones that are cached
      queryClient.getQueryData(['post', post.id])
      ? {
      fontWeight: 'bold',
      color: 'green',
      }
      : {}
      }
    • getQueryData performs an exact search against all queries in the cache.
    • exact searches try to compare query hashes:
      if (exact) {
      if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
      return false
      }
    • now the query we pass in here is the one that exists (['posts']), which is the one with the custom queryKeyHashFn.
    • BUT the queryKey we want to compare it to is something like ['post', 29]. So now we take ['post', 29] and we hash it with the options from the ['posts'] query.

    Note that this doesn't really affect useQuery calls as your issue states, this is only for matching a query against another query, which is what getQueryData does.

    Tbh, the only use-cases I have seen for a custom hashFn was to set it globally to allow for non-serializable values. What's your use-case where you have to set this on a per-query basis?


    We could say the behaviour to perform the hash of the queries to test with the hashing function of the Query we're currently comparing against is wrong and just use the default hashKey method, but this would lead to no query being found if that query actually uses a custom hashFn. So, I don't see a way to "fix" this right now.

  2. zirkelc commented on Oct 30, 2023

    @zirkelc
    Author

    @TkDodo thanks for the explanation, that makes sense.

    I'm using tRPC and its React Query integration, so the query key components are determined by tRPC.
    I have query procedure listPosts which accepts some generic parameters and and optional lastUpdatedAt timestamp.
    The query key looks something like this:

    [["posts","list"],{"input":{ "parameters": {} },"type":"query"}]
    

    This query is expensive, so I cache it also on the server with the given parameters as caching key in case multiple clients request the same data. When I receive the same parameters on the server, I return the data from the cache.

    Now I need some way for clients to force a refresh on the server returning new data instead of cached data for the same parameters. So in this case, I query the listPosts with an optional lastUpdatedAt timestamp. The query key is now:

    [["posts","list"],{"input":{ "parameters": {}, "lastUpdatedAt": 123456789 },"type":"query"}]
    

    The servers receives the same parameters as before and finds the data in the cache, but the lastUpdatedAt timestamp is greater than the cached timestamp. So it runs the expensive operation on the server and returns the new data (and caches it).

    Now I have two query keys on the client which are logically the same. I must update the query data of key 1 and key 2 with new data, because query key 2 is only temporary to trigger a server cache-invalidation. The lastUpdatedAt that I sent in query key 2 is a local state that will get lost after page navigation. When I later get back to the ListPosts page, it will use query key 1 again with data which was maybe set by query key 2.

    I'm currently using onSuccess of useQuery to set the query data of all query keys matching:

    [["posts","list"],{"input":{ "parameters": {} },"type":"query"}]
    

    That means it sets the data for query key 1 (without lastUpdatedAt) and 2 (with lastUpdatedAt).

    I know that onSuccess was deprecated in v5, so I'm looking for an alternative option. The queryKeyHashFn sounded like it would allow me to manipulate the query key components (provided by tRPC) and simply remove the lastUpdatedAt from the key (but keep it in the input). This way, I would only have query key 1 and the result from the server would always update this one query key. Furthermore, because I only have query key 1 which is always the same from React Query's perspective, I assume I would have to use refetch() to trigger a request to the server with a new lastUpdatedAt in the request payload.


    The other alternative would be to have an option on tRPC to change the way it constructs its query keys. But I think they would refer me directly to the `queryKeyHashFn option.

  3. TkDodo commented on Oct 30, 2023

    @TkDodo
    Collaborator

    Now I need some way for clients to force a refresh on the server returning new data instead of cached data for the same parameters

    If you really must do that, I would put lastUpdatedAt into the meta field. Not sure if trpc supports this though. Values in meta are passed to the queryFn without being part of the key.

    Otherwise, invalidating the cache on the server seems like a mutation to me that you can fire?

  4. zirkelc commented on Oct 30, 2023

    @zirkelc
    Author

    Thanks, I will investigate this further. I assume, as a last resort, I could also use data from useQuery as deps for useEffect to synchronize all query keys when new data was fetched?

    Yes, invalidation sounds like a good fit for a mutations. I didn't go that way, because I'm using DynamoDB to cache the data and the reads are eventually consistent. That means I can't guarantee that the request after the cache invalidation will receive the newest data (= no data).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions