Skip to content
Source
Sign inSign up
TanStack/query

[Bug] Persisted query without observers does not respect stale time #9233

ClosedNick-Motion(GitHub profile, opens in a new tab) opened this issue 5 comments

Describe the bug

// experimental_createQueryPersister
 const restoredData = await retrieveQuery(
        query.queryHash,
        (persistedQuery) => {
          query.setState({
            dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
            errorUpdatedAt: persistedQuery.state.errorUpdatedAt
          });
          if (query.isStale()) {
            query.fetch();
          }
        }
      );

// query.js
  isStale() {
    if (this.getObserversCount() > 0) {
      return this.observers.some(
        (observer) => observer.getCurrentResult().isStale
      );
    }
    return this.state.data === void 0 || this.state.isInvalidated;
  }
  1. When restoring a persisted query, a callback is passed, which is called after retrieving the query data.
  2. The isStale() method checks if there are observers, and if so, uses their staleness calculation. If there are no observers, it falls back to checking this.state.data === undefined || this.state.isInvalidated.
  3. But in a prefetch scenario, when a query is restored from persistence, it may not have observers yet. And neither of the other checks may be true.
  4. So because isStale does not do a time-based staleness check, it returns false in this check, even when the query should be considered stale when considering its staleTime & dataUpdatedAt.
  5. So the stale persisted query is not lazily refetched after restoring <-- bug.

This does not match the behavior described in the docs:

staleTime is also respected after restoring the Query, so if data is considered stale, it will be refetched immediately after restoring.

https://tanstack.com/query/latest/docs/framework/react/plugins/createPersister

To fix: consider time-based staleness:

 const restoredData = await retrieveQuery(
        query.queryHash,
        (persistedQuery) => {
          query.setState({
            dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
            errorUpdatedAt: persistedQuery.state.errorUpdatedAt
          });
          const resolvedStaleTime = typeof query.options.staleTime === "function"
              ? query.options.staleTime(query)
              : query.options.staleTime;
          if (query.isStale() || query.isStaleByTime(resolvedStaleTime)) {
            query.fetch();
          }
        }
      );

This works - the only issue is from Typescript, as staleTime is in fact defined on query.options, but not in the QueryOptions type. We don't want to check the staleTime of the observers - as the bug stems from the fact that there might not be any at the point we restore the query.

Your minimal, reproducible example

N/A

Steps to reproduce

  1. Persist query with staleTime
  2. Prefetch query before observer rendered
  3. See query restored but not refetched, staleTime not respected

Expected behavior

Prefetched persisted queries should respect staleTime when determining staleness in persist refetch.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

OS: macOS 14.6 Browser: latest chrome

Tanstack Query adapter

react-query

TanStack Query version

5.79.0

TypeScript version

5.8.2

Additional context

No response

  1. TkDodocommented

    A query can only be stale by time when there are observers, as stale-ness depends on how you look at it. A query can in fact not be stale without an observer - that’s why query.options does’t have it.

    query.options.staleTime

    don’t rely on it! It’s only there at runtime if you inspect the options object because we spread all options we pass in instead of removing excess properties, as TypeScript doesn’t mind excess properties. This is not guaranteed behaviour, and also might not have the correct value if you use different staleTimes.

    staleTime is also respected after restoring the Query, so if data is considered stale, it will be refetched immediately after restoring.

    that sentence refers to what we do internally in the persister when using it on useQuery.


    looking at this code in isolation:

     const restoredData = await retrieveQuery(
      query.queryHash,
      (persistedQuery) => {
        query.setState({
          dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
          errorUpdatedAt: persistedQuery.state.errorUpdatedAt
        });
      }
    );

    which staleTime should be taken for the query here if you have no observer? The query has data, and we know when the data was created, but we don’t know when it should be considered stale because without observers, there is nothing that tells us what staleTime should be. The fact that you see query.options.staleTime implies that you, at some point, had an observer mounted with a staleTime or maybe used queryClient.prefetchQuery() which used one. But again, those are observer specific and not stored on a query, it’s also not persisted to the external storage.


    What you want instead if likely to use queryClient.fetchQuery, and pass a staleTime to it to indicate when you should trigger a refetch:

     const restoredData = await retrieveQuery(
      query.queryHash,
      (persistedQuery) => {
        query.setState({
          dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
          errorUpdatedAt: persistedQuery.state.errorUpdatedAt
        });
        // refetch if the restored data is older than 2 minutes:
        void queryClient.fetchQuery({ queryKey, queryFn, staleTime: 2 * 60 * 1000 })
      }
    );
  2. TkDodo closed this

  3. TkDodo added labelsworks as designed

  4. Thanks for your detailed response.

    I believe there is an issue. You are correct, my use is in prefetching before observers are mounted:

    await client.prefetchQuery(queryOptions)

    Called during app bootstrap with a staleTime defined in a configuration object. This is in effect equivalent to the recommendation of using fetchQuery with staleTime.

    My call chain is:

    prefetchQuery
      → fetchQuery
        → [if query.isStaleByTime === true] // query is stale by time
          → query.fetch
            → fetchFn
              → this.options.persister
                → persisterFn
                  → [if query.isStale() === false] // query is not stale and not refetched

    And those two stale checks not matching illustrate the problem.

    A query can in fact not be stale without an observer

    This doesn't seem like it ought to be true, as the call to query.isStaleByTime in fetchQuery shows:

      fetchQuery(options) {
        ...
        return query.isStaleByTime(
          resolveStaleTime(defaultedOptions.staleTime, query) // <---- no observer, but can be stale
        ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
      }

    ...which staleTime should be taken for the query here if you have no observer?

    In this case, the staleTime passed to prefetchQuery. The issue of requiring an observer to supply staleTime seems to narrow too much - shouldn't the concept be instead whatever the caller supplied, whether an observer or a client method?

  5. TkDodocommented

    This doesn't seem like it ought to be true

    okay, let me rephrase it then. A query doesn’t know if it’s stale or not, because that depends on call sides providing that information. Observers have that information. fetchQuery and prefetchQuery also have that information, as they understand staleTime and have this added explicitly to their types:

    https://github.com/TanStack/query/blob/efa963d1fd90d408d3500ef8754c78fb243b9473/packages/query-core/src/types.ts#L502-L507

    The staleTime you pass to fetchQuery is not stored on the Query. After fetchQuery is done, that staleTime you passed is gone. Same goes for observers: they are stored on observers, but as soon as the observer unmounts, the query knows nothing about the staleTime this observer had.

    My call chain is:

    Note the two differences in your call chain:

    • query.isStaleByTime needs a time to be passed in, and computes it from there
    • query.isStale() operates on the query only, with the information it has. That is only mounted observers / data, not previous calls to imperative methods.
  6. Those are great clarifications, as a description of current state. I still do think, as an end user, the current state does not match my expectations of how it should operate - the internals of "what owns staleTime" should not matter to the consumer. I would expect "staleness" to mean the same thing, with the same effects, regardless of what's doing the calling. But as this seems to be an intentional design decision, I'll note this and move on.

    Thank you for engaging - your work on this library has been invaluable and I much appreciate it.

  7. TkDodocommented

    thanks, this is one of the limitations that we’re currently have to accept. Maybe we can make the docs better?

    FWIW, I tried moving staleTime to the query twice already and couldn’t make it work, and we also got feedback that staleTime on a per-observer basis is a “feature”.

Sign in to join this conversation.