Skip to content
Source
Sign inSign up
TanStack/db

Tanstack Query keys not properly tracked #1385

Send to my agent
Closedkevin-dp(GitHub profile, opens in a new tab) opened this issue 1 comment

updateCacheData uses queryKey({}) as base key — may miss cache entries with function-based queryKey

Summary

updateCacheData assumes that queryKey({}) produces a key that is a prefix of all derived query keys. This assumption doesn't hold for all function-based queryKey implementations, which means some cache entries may not be updated when syncedData changes via manual write operations (writeInsert/writeUpdate/writeDelete).

How it happens

When updateCacheData needs to update cache entries that are no longer tracked in hashToQueryKey (e.g. stale entries from destroyed observers), it computes a base key to query the TQ cache:

const baseKey = typeof queryKey === 'function' ? queryKey({}) : queryKey

TanStack Query's findAll({ queryKey: baseKey }) uses prefix matching — it returns all cached queries whose key starts with baseKey.

This works when the function-based queryKey follows a prefix pattern:

// ✅ Works: base key ['items'] is a prefix of all derived keys
queryKey: (opts) => {
  if (opts.where) {
    return ['items', JSON.stringify(opts.where)]
  }
  return ['items']
}

But breaks when it doesn't:

// ❌ Breaks: ['items-all'] is NOT a prefix of ['items-filtered', ...]
queryKey: (opts) => {
  if (opts.where) {
    return ['items-filtered', JSON.stringify(opts.where)]
  }
  return ['items-all']
}

In the broken case, findAll({ queryKey: ['items-all'] }) won't match ['items-filtered', ...], so those cache entries are never updated and can contain stale data.

Proposed fix

Track all query keys ever created by a collection in a Map<string, QueryKey> (hash → key) that is never pruned. Use this map in updateCacheData instead of computing a base key and relying on prefix matching. This is robust regardless of how the queryKey function is implemented.

  1. Discussed this with @samwillis, TanStack Query is designed to work with these prefixes on the query keys. So let's enforce this requirement instead, i.e. document it + warn user at runtime if they violate this assumption.

Sign in to join this conversation.