v1.7.0 #1821
markerikson
announced in
Announcements
v1.7.0
#1821
Replies: 1 comment 6 replies
-
Is this a typo (here and in the docs)? It seems that it should be Also seeing an issue that if you re-render, a new promise replaces the initial promise using a new // initial render
let html = ReactDOMServer.renderToString(element);
let promises = api.util.getRunningOperationPromises();
while (promises.length > 0) {
// wait for all API requests
await Promise.all(promises);
// re-render after API requests are completed
html = ReactDOMServer.renderToString(element);
// check if re-render resulted in more promises to await
promises = api.util.getRunningOperationPromises();
}
// ensure that no rogue timers are left running.
store.dispatch(api.util.resetApiState());
return html; |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This feature release has a wide variety of API improvements:
currentData
field to query resultscondition
options increateAsyncThunk
createSlice/createReducer
to accept a "lazy state initializer" functioncreateSlice
to avoid potential circular dependency issues by lazy-building its reducerChangelog
RTK Query
RTK Query SSR and Rehydration Support
RTK Query now has support for SSR scenarios, such as the
getStaticProps/getServerSideProps
APIs in Next.js. Queries can be executed on the server using the existingdispatch(someEndpoint.initiate())
thunks, and then collected using the newawait Promise.all(api.getRunningOperationPromises())
method.API definitions can then provide an
extractRehydrationInfo
method that looks for a specific action type containing the fetched data, and return the data to initialize the API cache section of the store state.The related
api.util.getRunningOperationPromise()
API adds a building block that may enable future support for React Suspense as well, and we'd encourage users to experiment with this idea.Sharing Mutation Results Across Components
Mutation hooks provide status of in-progress requests, but as originally designed that information was unique per-component - there was no way for another component to see that request status data. But, we had several requests to enable this use case.
useMutation
hooks now support afixedCacheKey
option that will store the result status in a common location, so multiple components can read the request status if needed.This does mean that the data cannot easily be cleaned up automatically, so the mutation status object now includes a
reset()
function that can be used to clear that data.Data Loading Updates
Query results now include a
currentData
field, which contains the latest data cached from the server for the current query arg. Additionally,transformResponse
now receives the query arg as a parameter. These can be used to add additional derivation logic in cases when a hooks query arg has changed to represent a different value and the existing data no longer conceptually makes sense to keep displaying.Data Serialization and Base Query Improvements
RTK Query originally only did shallow checks for query arg fields to determine if values had changed. This caused issues with infinite loops depending on user input.
The query hooks now use a "serialized stable value" hook internally to do more consistent comparisons of query args and eliminate those problems.
Also,
fetchBaseQuery
now supports aparamsSerializer
option that allows customization of query string generation from the provided arguments, which enables better interaction with some backend APIs.The
BaseQueryApi
andprepareheaders
args now include fields forendpoint
name,type
to indicate if it's a query or mutation, andforced
to indicate a re-fetch even if there was already a cache entry. These can be used to help determine headers likeCache-Control: no-cache
.Other RTK Query Improvements
API objects now have a
selectInvalidatedBy
function that accepts a root state object and an array of query tag objects, and returns a list of details on endpoints that would be invalidated. This can be used to help implement optimistic updates of paginated lists.Fixed an issue serializing a query arg of
undefined
. Related, an empty JSON body now is stored asnull
instead ofundefined
.There are now dev warnings for potential mistakes in endpoint setup, like a query function that does not return a
data
field.Lazy query trigger promises can now be unwrapped similar to mutations.
Fixed a type error that led the endpoint return type to be erroneously used as a state key, which caused generated selectors to have an inferred
state: never
argument.Fixed
transformResponse
to correctly receive theoriginalArgs
as its third parameter.api.util.resetApiState
will now clear out cached values inuseQuery
hooks.The
RetryOptions
interface is now exported, which resolves a TS build error when using the hooks with TS declarations.RTK Core
createSlice
Lazy Reducers and Circular DependenciesFor the last couple years we've specifically recommended using a "feature folder" structure with a single "slice" file of logic per feature, and
createSlice
makes that pattern really easy - no need to have separate folders and files for/actions
and/constants
any more.The one downside to the "slice file" pattern is in cases when slice A needs to import actions from slice B to respond to them, and slice B also needs to listen to slice A. This circular import then causes runtime errors, because one of the modules will not have finished initializing by the time the other executes the module body. That causes the exports to be undefined, and
createSlice
throws an error because you can't passundefined
tobuilder.addCase()
inextraReducers
. (Or, worse, there's no obvious error and things break later.)There are well-known patterns for breaking circular dependencies, typically requiring extracting shared logic into a separate file. For RTK, this usually means calling
createAction
separately, and importing those action creators into both slices.While this is a rarer problem, it's one that can happen in real usage, and it's also been a semi-frequently listed concern from users who didn't want to use RTK.
We've updated
createSlice
to now lazily create its reducer function the first time you try to call it. That delay in instantiation should eliminate circular dependencies as a runtime error increateSlice
.createAsyncThunk
ImprovementsThe
condition
option may now beasync
, which enables scenarios like checking if an existing operation is running and resolving the promise when the other instance is done.If an
idGenerator
function is provided, it will now be given thethunkArg
value as a parameter, which enables generating custom IDs based on the request data.The
createAsyncThunk
types were updated to correctly handle type inference when usingrejectWithValue()
.Other RTK Improvements
createSlice
andcreateReducer
now accept a "lazy state initializer" function as theinitialState
argument. If provided, the initializer will be called to produce a new initial state value any time the reducer is givenundefined
as its state argument. This can be useful for cases like reading fromlocalStorage
, as well as testing.The
isPlainObject
util has been updated to match the implementation in other Redux libs.The UMD builds of RTK Query now attach as
window.RTKQ
instead of overwritingwindow.RTK
.Fixed an issue with sourcemap loading due to an incorrect filename replacement.
Dependency Updates
We've updated our deps to the latest versions:
Dispatch
everywhere in the appWe've also lowered RTK's peer dependency on React from
^16.14
to^16.9
, as we just need hooks to be available.Other Redux Development Work
The Redux team has also been working on several other updates to the Redux family of libraries.
React-Redux v8.0 Beta
We've rewritten React-Redux to add compatibility with the upcoming React 18 release and converted its codebase to TypeScript. It still supports React 16.8+/17 via a
/compat
entry point. We'd appreciate further testing from the community so we can confirm it works as expected in real apps before final release. For details on the changes, see:RTK "Action Listener Middleware" Alpha
We have been working on a new "action listener middleware" that we hope to release in an upcoming version of RTK. It's designed to let users write code that runs in response to dispatched actions and state changes, including simple callbacks and moderately complex async workflows. The current design appears capable of handling many of the use cases that previously required use of the Redux-Saga or Redux-Observable middlewares, but with a smaller bundle size and simpler API.
The listener middleware is still in alpha, but we'd really appreciate more users testing it out and giving us additional feedback to help us finalize the API and make sure it covers the right use cases.
RTK Query CodeGen
The RTK Query OpenAPI codegen tool has been rewritten with new options and improved output.
What's Changed
true
" isLoading briefly flips back totrue
#1519 by @phryneas in fix "isLoading briefly flips back totrue
" #1519 #1520arg
totransformResponse
by @phryneas in addarg
totransformResponse
#1521currentData
property to hook results. by @phryneas in addcurrentData
property to hook results. #1500useSerializedStableValue
for value comparison by @phryneas in useuseSerializedStableValue
for value comparison #1533reset
method to useMutation hook by @phryneas in addreset
method to useMutation hook #1476useMutation
hook by @phryneas in allow for "shared component results" using theuseMutation
hook #1477useMutation
shared results by @Shrugsy in 🐛 Fix bug withuseMutation
shared results #1616endpoint
,type
andforced
toBaseQueryApi
andprepareHeaders
by @phryneas in addendpoint
,type
andforced
toBaseQueryApi
andprepareHeaders
#1656AsyncThunkConfig
for better inference by @phryneas in split off signature withoutAsyncThunkConfig
for better inference #1644selectInvalidatedBy
by @phryneas in addselectInvalidatedBy
#1665null
on empty body for JSON. Add DevWarnings. #1699null
as a valid plain object prototype inisPlainObject()
in order to sync the util acrossreduxjs/*
repositories #1734RetryOptions
interface fromretry.ts
#1751Full Changelog: v1.6.2...v1.7.0
This discussion was created from the release v1.7.0.
Beta Was this translation helpful? Give feedback.
All reactions