invalidateQueries should preserve refetch intent during initial fetch

Đang mở
#11,526 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
35/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Sôi nổi
Công nghệ
typescript
Lĩnh vực
api, backend-api-design

Hướng nghiên cứu

Bắt đầu bằng cách theo dõi queryClient.invalidateQueries trong lần fetch ban đầu và xem lại cuộc thảo luận trước đó trong #8530. Xác định các bài kiểm thử cho việc invalidation lặp lại, hành vi refetch ở cuối và việc hủy, sau đó xác định cách chỉ định policy toàn cục và override theo từng lần gọi; được xem là hoàn thành khi ý định invalidation không bị mất và hành vi latency đã chọn được bao phủ.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

AI-assisted issue: Written in GitHub Copilot, configured to GPT-5.6 Sol Medium, under close supervision of a frontend lead software engineer with 10+ years of experience. I spent roughly a full day reproducing this behavior and working back and forth with AI to understand the implementation, history, trade-offs, and alternatives. I therefore have high personal confidence in the core problem and proposed direction. Some API details may still need refinement, but I believe the substance is worth considering.

Problem

invalidateQueries() can effectively lose its refetch intent when called during an initial fetch.

The query is marked invalid, but the attempted refetch reuses the existing in-flight promise because no cached data exists yet. After that request settles, no trailing refetch occurs.

Data fetched from a server state predating the invalidation can therefore become the settled cache value indefinitely.

This was previously discussed in #8530. That discussion focused primarily on whether the initial request should be cancelled. I think cancellation and invalidation intent should be treated separately:

  • Cancellation determines how quickly the client reaches any usable state versus the final state.
  • Invalidation means the current result is no longer trusted and should eventually cause a fetch started after invalidation.
Real-world impact

We encountered this with a long-running data-check query:

  1. Query starts while server data is in state A.
  2. User changes server data to state B before query finishes.
  3. Mutation succeeds and invalidates the data-check query.
  4. Because the query is still performing its initial fetch, invalidation reuses that request.
  5. Original request returns a result based on state A.
  6. UI settles on that result even though backend is now in state B.

From user perspective, successful change appears not to have worked. UI contradicts current backend state solely because of request timing.

A loading indicator does not solve this. Loading ends when original request completes, but stale result remains cached without a subsequent request.

Expected invariant

Invalidation should be durable intent:

A fetch that started before an invalidation should not permanently satisfy that invalidation.

This does not necessarily mean initial fetch must be cancelled. Two useful strategies exist.

Strategy 1: first usable state sooner

Allow current fetch to complete, then perform one trailing refetch:

fetch A starts
invalidate
invalidate
fetch A completes and provides first usable state
fetch B starts once
fetch B completes with current state

Multiple invalidations should coalesce into one trailing refetch.

Benefits:

  • Same time-to-first-result as current behavior.
  • Avoids extending initial loading state.
  • Eventually converges to data fetched after invalidation.
  • Fits stale-while-revalidate behavior well.

This seems like a reasonable default.

Strategy 2: final state sooner

Cancel current fetch and immediately start a replacement:

fetch A starts
invalidate
fetch A is cancelled
fetch B starts immediately
fetch B completes with current state

Benefits:

  • Reaches current final state sooner.
  • Never commits known-outdated result.
  • Useful for status indicators and other correctness-sensitive queries.

Trade-off: user waits longer for any usable result.

Proposed API direction

Expose this as a global/defaultable query-client policy, with per-call override:

new QueryClient({
  defaultOptions: {
    queries: {
      invalidationBehavior: 'queue',
    },
  },
})

queryClient.invalidateQueries(filters, {
  invalidationBehavior: 'cancel',
})

Exact option and value names need design work. Names should communicate the latency choice:

  • Prioritize first usable state, then revalidate.
  • Prioritize final post-invalidation state.
  • Preserve current behavior, where the in-flight initial result is accepted without trailing work.

I do not have a good concise name for the third behavior yet. reuse and deduplicate describe implementation details rather than the freshness consequence.

I would avoid adding a none value here. refetchType: 'none' already represents mark-stale-without-refetch behavior.

Why both invariant and option matter

Automatically scheduling a trailing refetch fixes lost invalidation, but only provides the first-usable-state-sooner strategy.

Some applications need final-state-as-soon-as-possible behavior. They should not need to manually coordinate cancelQueries() followed by invalidateQueries() at every call site.

A global policy plus per-call override provides both:

  • Safe eventual-freshness default.
  • Explicit low-latency path to final state.
  • No ignored invalidation intent.
Ngôn ngữ chính
TypeScript
Star
50.3k
Fork
4.2k
Merge trung bình
20 giờ 49 phút
Pull request đã merge (30 ngày)
205

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của TanStack/query

Tất cả issue của TanStack/query

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.