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
Uh oh!
There was an error while loading. Please reload this page.
-
This feature release has a wide variety of API improvements:
currentDatafield to query resultsconditionoptions increateAsyncThunkcreateSlice/createReducerto accept a "lazy state initializer" functioncreateSliceto 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/getServerSidePropsAPIs 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
extractRehydrationInfomethod 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.
useMutationhooks now support afixedCacheKeyoption 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
currentDatafield, which contains the latest data cached from the server for the current query arg. Additionally,transformResponsenow 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,
fetchBaseQuerynow supports aparamsSerializeroption that allows customization of query string generation from the provided arguments, which enables better interaction with some backend APIs.The
BaseQueryApiandprepareheadersargs now include fields forendpointname,typeto indicate if it's a query or mutation, andforcedto 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
selectInvalidatedByfunction 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 asnullinstead ofundefined.There are now dev warnings for potential mistakes in endpoint setup, like a query function that does not return a
datafield.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: neverargument.Fixed
transformResponseto correctly receive theoriginalArgsas its third parameter.api.util.resetApiStatewill now clear out cached values inuseQueryhooks.The
RetryOptionsinterface is now exported, which resolves a TS build error when using the hooks with TS declarations.RTK Core
createSliceLazy 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
createSlicemakes that pattern really easy - no need to have separate folders and files for/actionsand/constantsany 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
createSlicethrows an error because you can't passundefinedtobuilder.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
createActionseparately, 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
createSliceto 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.createAsyncThunkImprovementsThe
conditionoption 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
idGeneratorfunction is provided, it will now be given thethunkArgvalue as a parameter, which enables generating custom IDs based on the request data.The
createAsyncThunktypes were updated to correctly handle type inference when usingrejectWithValue().Other RTK Improvements
createSliceandcreateReducernow accept a "lazy state initializer" function as theinitialStateargument. If provided, the initializer will be called to produce a new initial state value any time the reducer is givenundefinedas its state argument. This can be useful for cases like reading fromlocalStorage, as well as testing.The
isPlainObjectutil has been updated to match the implementation in other Redux libs.The UMD builds of RTK Query now attach as
window.RTKQinstead 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:
Dispatcheverywhere in the appWe've also lowered RTK's peer dependency on React from
^16.14to^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
/compatentry 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 #1520argtotransformResponseby @phryneas in addargtotransformResponse#1521currentDataproperty to hook results. by @phryneas in addcurrentDataproperty to hook results. #1500useSerializedStableValuefor value comparison by @phryneas in useuseSerializedStableValuefor value comparison #1533resetmethod to useMutation hook by @phryneas in addresetmethod to useMutation hook #1476useMutationhook by @phryneas in allow for "shared component results" using theuseMutationhook #1477useMutationshared results by @Shrugsy in 🐛 Fix bug withuseMutationshared results #1616endpoint,typeandforcedtoBaseQueryApiandprepareHeadersby @phryneas in addendpoint,typeandforcedtoBaseQueryApiandprepareHeaders#1656AsyncThunkConfigfor better inference by @phryneas in split off signature withoutAsyncThunkConfigfor better inference #1644selectInvalidatedByby @phryneas in addselectInvalidatedBy#1665nullon empty body for JSON. Add DevWarnings. #1699nullas a valid plain object prototype inisPlainObject()in order to sync the util acrossreduxjs/*repositories #1734RetryOptionsinterface 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