Vai al contenuto
verdict:

Redux Toolkit 2.15.0

notable

note: la sintesi e le note di rilascio sono in inglese

pending: sintesi in attesa

Rilevata il 2026-11-19 alle 13:08 UTC. La sintesi viene scritta al prossimo aggiornamento; le note di rilascio complete sono già qui sotto.

release-notesgithub.com/reduxjs/redux-toolkit · 218 righe
  1. This **feature release** gives each store its own RTK Query middleware runtime, makes `initiate()` promises resolve with their own request's result, adds several new options to RTK Query, improves listener middleware fork child capabilities, improves readability for several RTK type definitions, and fixes a variety of RTKQ bugs.
  2. This release continues the work from our [roadmap to Redux Toolkit 3.0](https://github.com/reduxjs/redux-toolkit/discussions/5536). Several of the RTK Query changes here are bug fixes that change behavior in edge cases, so **please read the "Behavior Changes" notes below**.
  3. ## Changelog
  4. ### Per-Store RTK Query Runtime
  5. RTK Query's middleware keeps a lot of state outside the Redux store in order to manage requests and cache lifetimes: subscriber counts, running requests, poll and cache collection timers, and cache lifecycle promises. That state used to live in closures shared by every store that used the same `api` object. That was fine for a single client-side store, but caused problems for SSR and tests, where many stores share one `api`.
  6. Each store now gets its own consolidated internal runtime state, created by the API middleware. `resetApiState` now calls `runtime.reset()`, which clears every subscriber, timer and cache lifecycle for that store, aborts running requests, and clears pending tag invalidations. It no longer touches other stores.
  7. Internally, each cache key now has one record that tracks its running request, timers and lifecycle, and all removals go through a single path. That made the `initiate()` fixes below possible.
  8. The missing-middleware check now runs once per store, and looks for the store's runtime instead of dispatching an internal action. This check is stricter: an api whose middleware is missing now throws even if another api with the same `reducerPath` has its middleware in the store.
  9. ### `initiate()` Promises Resolve With Their Own Result
  10. We had several long-standing reports ([#5506](https://github.com/reduxjs/redux-toolkit/issues/5506), [#4833](https://github.com/reduxjs/redux-toolkit/issues/4833), [#5173](https://github.com/reduxjs/redux-toolkit/issues/5173), [#5346](https://github.com/reduxjs/redux-toolkit/issues/5346)) that the promise from `initiate()` could resolve with `undefined`, or with a _different_ request's data. That happened when the cache entry was removed, reset, invalidated or replaced while the request was running, because the promise read the cache entry after the request finished instead of the request's own result.
  11. We've done a thorough review of the promise resolution logic to analyze the current intended behavior, ran separate formal modeling of the derived behavior to help uncover gaps, updated the model to fill those gaps, and reworked that logic to fully comply with the improved expected behavior.
  12. Each `initiate()` promise now resolves with its own request's result, captured as soon as that request's `fulfilled` or `rejected` action reaches the store.
  13. Thanks to @kkatalz ([#5474](https://github.com/reduxjs/redux-toolkit/pull/5474)) and @rajanpanth ([#5347](https://github.com/reduxjs/redux-toolkit/pull/5347)): both PRs fixed part of this, and their tests are included.
  14. #### Behavior Changes
  15. These ship in 2.x as bug fixes, but code that depended on the old behavior will see a difference:
  16. - **Removing a cache entry while its request runs now aborts that request.** This covers `removeQueryResult`, a lazy query's `reset()`, cache collection, and `resetApiState`. The `initiate()` promise resolves with `isError: true` and an `AbortError` whose message is `'removed'` or `'reset'`. **That means `unwrap()` now rejects in this case, where it used to resolve with stale or missing data.** The plain promise still never rejects.
  17. - **`queryFulfilled` in `onQueryStarted` rejects in the same case. If your `onQueryStarted` does `await queryFulfilled` without a `try/catch`, you'll now get an unhandled rejection when the entry is removed mid-request.** Wrap it:
  18. ```ts
  19. async onQueryStarted(arg, { queryFulfilled }) {
  20. try {
  21. const { data } = await queryFulfilled
  22. // ...
  23. } catch {
  24. // request failed, or the cache entry was removed while it ran
  25. }
  26. }
  27. ```
  28. - Invalidating an entry that has a running request (by tags, or a focus/reconnect refetch) now waits for that request to finish. The running request's promise gets its own result, and then the entry refetches if it has subscribers, or is removed if it doesn't.
  29. - A refetch while a request is running joins that request instead of starting another one. `initiate()` also joins a running `upsertQueryData`.
  30. - A `pending` entry restored from persisted state, with no request actually running, now fetches again.
  31. `onCacheEntryAdded` has a new `getCacheEntryRemovedReason()` function that returns `'reset'` if the entry was removed by `resetApiState`, `'removed'` for any other removal, or `undefined` while the entry is still in the cache. `cacheEntryRemoved` stays a `Promise<void>`, since many apps declare that type in their own handler types.
  32. ```ts
  33. async onCacheEntryAdded(arg, { cacheEntryRemoved, getCacheEntryRemovedReason }) {
  34. const connection = openConnection(arg)
  35. await cacheEntryRemoved
  36. if (getCacheEntryRemovedReason() !== 'reset') {
  37. connection.unsubscribe()
  38. }
  39. connection.close()
  40. }
  41. ```
  42. ### `startReason` for Query Requests
  43. We've had a request ([#4757](https://github.com/reduxjs/redux-toolkit/issues/4757)) to know _why_ a query is fetching. For example, a `queryFn` might want to read from the primary database after a tag invalidation, instead of a replica that may be behind.
  44. `baseQuery` / `queryFn` (via `BaseQueryApi`), `fetchBaseQuery`'s `prepareHeaders`, `onQueryStarted` and `onCacheEntryAdded` now receive a `startReason`. The new `QueryStartReason` type is `'initial' | 'refetch' | 'invalidation' | 'poll' | 'focus' | 'reconnect' | 'upsert' | 'hydrate' | 'nextPage' | 'previousPage'`.
  45. ```ts
  46. const api = createApi({
  47. baseQuery: fetchBaseQuery({
  48. baseUrl: '/api',
  49. prepareHeaders: (headers, { startReason }) => {
  50. if (startReason === 'invalidation') {
  51. headers.set('x-read-from-primary', 'true')
  52. }
  53. return headers
  54. },
  55. }),
  56. endpoints: () => ({}),
  57. })
  58. ```
  59. A few details: `'initial'` vs `'refetch'` depends on whether the entry already has data. Mutations get `startReason: undefined`. `'hydrate'` is reserved for upcoming hydration work and isn't set yet. We may add additional values in the future if needed.
  60. ### Function `pollingInterval`
  61. `pollingInterval` can now be a function that receives the current cache entry and returns an interval in ms ([#2639](https://github.com/reduxjs/redux-toolkit/issues/2639)). This covers "poll while a job is running, stop when it's done" without a second hook:
  62. ```ts
  63. useGetJobQuery(id, {
  64. pollingInterval: ({ data }) => (data?.status === 'running' ? 1000 : 0),
  65. })
  66. ```
  67. It works in all the query hooks, `initiate()` and `updateSubscriptionOptions`. The function runs once per cache key when the next poll is scheduled after a request settles. When several subscribers poll the same key, the lowest result wins, the same as numeric intervals. Returning `0`, a negative number or a non-number means "don't poll", and polling resumes if a later request makes the function return an interval again. An inline function in a hook doesn't dispatch `updateSubscriptionOptions` on every render.
  68. Related changes:
  69. - A negative numeric `pollingInterval` now means "no polling". Before, it re-polled immediately in a loop.
  70. - `'payload.options.pollingInterval'` is a new default entry in the serializability check's `ignoredActionPaths`. If you pass your own `ignoredActionPaths`, you'll need to add it.
  71. - `SubscriptionOptions['pollingInterval']` is now `number | ((entry) => number)`, so code that reads it as a `number` needs a type check. There's a new exported `PollingInterval` type.
  72. ### `getRunningQuery` and `retainFor`
  73. `api.endpoints.x.getRunningQuery(arg)` is a typed thunk for query and infinite query endpoints. Dispatching it returns the promise of the running request for that cache entry, or `undefined`. It's the same promise the `initiate()` call that started the request returned, and awaiting it doesn't add a subscription. It's the typed per-endpoint form of `api.util.getRunningQueryThunk`.
  74. Query `initiate()` has a new `retainFor` option, in seconds. After the last subscriber leaves, the entry is kept for `Math.max(keepUnusedDataFor, retainFor)` seconds. This is useful for prefetching or `subscribe: false` requests whose data will be read soon:
  75. ```ts
  76. dispatch(api.endpoints.getPost.initiate(id, { subscribe: false, retainFor: 60 }))
  77. // later
  78. const running = dispatch(api.endpoints.getPost.getRunningQuery(id))
  79. if (running) {
  80. await running
  81. }
  82. ```
  83. There's also a new dev-only warning when an infinite query page fetch joins a running fetch in the other direction, like calling `fetchNextPage()` while `fetchPreviousPage()` is running. The second call still joins and doesn't fetch its own page, same as before.
  84. ### `getMiddlewareState()` and `isSubscribed()`
  85. The React hooks used to dispatch an internal `internal_getRTKQSubscriptions` action to check subscription status, and some libraries copied that pattern. We've added real APIs for it:
  86. - `api.util.getMiddlewareState()` is a thunk that returns read-only access to what the middleware tracks for that store (currently `getSubscriptionCount(queryCacheKey)`), or `undefined` if the middleware isn't added ([#5501](https://github.com/reduxjs/redux-toolkit/issues/5501)).
  87. - Query `initiate()` results have an `isSubscribed()` method.
  88. The hooks use `isSubscribed()` now, and don't dispatch anything to check subscriptions. **The `internal_getRTKQSubscriptions` action is deprecated.** It still works in 2.x, but logs a one-time dev warning and will be removed in 3.0. If you maintain a library that dispatches it (such as a port of the RTKQ hooks to another framework), switch to `getMiddlewareState()` and `isSubscribed()`.
  89. The hooks also no longer run their own missing-middleware check. A hook with `skip: true` on a store without the API middleware no longer throws. A non-skipped hook still throws, from the check in `initiate()`.
  90. ### Listener Middleware: Nested Forks
  91. `ForkedTaskAPI` now has `getState`, `dispatch` and `fork`, so a forked task can read state, dispatch actions and start its own child tasks ([#3314](https://github.com/reduxjs/redux-toolkit/issues/3314)). Nested forks are cancelled when the task that forked them ends or is cancelled. A nested fork with `autoJoin: true` makes its parent wait for it before completing.
  92. ```ts
  93. listenerMiddleware.startListening({
  94. actionCreator: startSync,
  95. effect: async (action, listenerApi) => {
  96. listenerApi.fork(async (forkApi) => {
  97. const { userId } = forkApi.getState().auth
  98. forkApi.fork(
  99. async (childApi) => {
  100. childApi.dispatch(syncStarted(userId))
  101. },
  102. { autoJoin: true },
  103. )
  104. })
  105. },
  106. })
  107. ```
  108. `ForkedTaskAPI` and the task executor types have optional `State` and `DispatchType` generics, which flow through `startListening`, `addListener` and their `withTypes()` versions. Like the listener's own `getState` and `dispatch`, these aren't guarded after the task finishes. With some internal cleanup in the same PR, the listener middleware is slightly smaller even with the new API.
  109. ### Readable Editor Hovers
  110. Hovering over RTK and RTKQ types in an editor often showed a wall of text that the editor cut off at 500 characters, along with odd names like `Slice$1` and `IsAny`. We've added named types so hovers show a name instead of the full structure: `FetchBaseQueryFn`, `ApiUtil`, `ListenerMiddlewareDispatch`, `AsyncThunkPromise` and `ReactApiModules`. The query, mutation and infinite query selector result types were rewritten so TypeScript keeps their names. Some hover lengths, before and after:
  111. | Hover | Before | After |
  112. | --- | ---: | ---: |
  113. | `useMutation` tuple | 2508 | 386 |
  114. | `endpoints.getPost.select(...)` | 2399 | 602 |
  115. | `api.util` | 16102 | 471 |
  116. | `dispatch(thunk(...))` | 552 | 71 |
  117. These are type-only changes. Please let us know if the selector result rewrite causes problems in code that's generic over endpoint definitions.
  118. ### Refetch and Polling Option Fixes
  119. When several subscribers share a query, RTKQ combines their options. Some of those rules skipped refetches that a subscriber asked for ([#5583](https://github.com/reduxjs/redux-toolkit/issues/5583)). Each subscriber's options are now resolved before they're combined:
  120. - **`refetchOnMountOrArgChange: 0` and `forceRefetch: 0` now always refetch.** Before, `0` disabled the option.
  121. - `refetchOnFocus` and `refetchOnReconnect` refetch a shared query if any subscriber's own or inherited setting is `true`. One subscriber's `false` no longer turns it off for the others.
  122. - Polling skips while unfocused only if _every_ polling subscriber sets `skipPollingIfUnfocused`. Non-polling subscribers don't affect this.
  123. Thanks to @duckieeeduck for this fix!
  124. ### Other Fixes
  125. An endpoint's `maxRetries` now caps retries even when the api-level `retry()` has a `retryCondition`. The `retryCondition` still decides which errors retry (thanks @luantaraschi!).
  126. `retry.fail()` called inside a `backoff` function no longer nests the error inside `{ error, meta }` (thanks @dfedoryshchev!).
  127. `fetchBaseQuery`'s `timeout` now works when the request passes its own `signal` (thanks @wozhenbang2004!). Query parameters are now added before a URL `#fragment` instead of after it (thanks @henricop!). `FetchArgs.headers` now accepts `number` and `boolean` values, which are converted to strings. They already worked at runtime (thanks @emersion!).
  128. The entity adapter keeps the `ids` order when an update changes an entity's id (thanks @b84330808!).
  129. Wrapping `createSlice` in a generic helper now keeps the `prepare` callback's parameter types (thanks @kkatalz!).
  130. ### Docs Updates
  131. We've documented `getCacheEntryRemovedReason`, `startReason`, `getRunningQuery`, `retainFor`, `getMiddlewareState`, `isSubscribed`, function `pollingInterval` and nested forks, and fixed several smaller doc and JSDoc errors.
  132. ## What's Changed
  133. * Refactor RTKQ middleware state into a per-store runtime by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5569
  134. * Give each store its own RTKQ middleware runtime, with `reset()` by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5570
  135. * Add `getState`, `dispatch`, and `fork` to `ForkedTaskAPI` by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5572
  136. * Fix public type names shown in editor hovers (`Slice$1`, `IsAny`) by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5575
  137. * Add `api.util.getMiddlewareState()` and `isSubscribed()` on query `initiate()` results by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5579
  138. * Track each cache key's request, timers and lifecycle through record transitions by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5586
  139. * Resolve `initiate()` promises with their own request result, and remove entries through one path by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5587
  140. * Settle and abort every running request for a key when its entry is removed by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5589
  141. * Add named public types so editor hovers stay readable by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5576
  142. * Fix endpoint maxRetries being ignored with a retry() retryCondition by @luantaraschi in https://github.com/reduxjs/redux-toolkit/pull/5590
  143. * Add `startReason` to `BaseQueryApi` and query lifecycle APIs by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5601
  144. * Add `endpoint.getRunningQuery` and `initiate` `retainFor` option by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5602
  145. * Allow `pollingInterval` to be a function of the cache entry by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/5604
  146. * fix(toolkit): keep `prepare` parameter types when wrapping `createSlice` by @kkatalz in https://github.com/reduxjs/redux-toolkit/pull/5591
  147. * fix(entityAdapter): keep ids order when an update changes an entity id by @b84330808 in https://github.com/reduxjs/redux-toolkit/pull/5573
  148. * fix(toolkit): `fetchBaseQuery` timeouts when a request provides a signal by @wozhenbang2004 in https://github.com/reduxjs/redux-toolkit/pull/5595
  149. * Fix refetch defaults and shared polling preferences by @duckieeeduck in https://github.com/reduxjs/redux-toolkit/pull/5593
  150. * fix(toolkit): `retry.fail()` in a `backoff` function nesting the error in `{ error, meta }` by @dfedoryshchev in https://github.com/reduxjs/redux-toolkit/pull/5612
  151. * fix(query): append query parameters before URL fragments by @henricop in https://github.com/reduxjs/redux-toolkit/pull/5598
  152. * fix(query): allow boolean/number in headers by @emersion in https://github.com/reduxjs/redux-toolkit/pull/5621
  153. **Full Changelog**: https://github.com/reduxjs/redux-toolkit/compare/v2.14.0...v2.15.0

vedi su githubdetected 2026-11-19 via npm