ngrx-entity-relationship
ngrx-entity-relationship copied to clipboard
chore(deps): update dependency @reduxjs/toolkit to v1.8.3
This PR contains the following updates:
| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| @reduxjs/toolkit (source) | 1.7.1 -> 1.8.3 |
Release Notes
reduxjs/redux-toolkit
v1.8.3
This bugfix release fixes a few minor issues and bits of behavior, including updating the React-Redux peer dep to ^8.0.2 final, stable sorting in createEntityAdapter.updateMany and some initial state handling in createSlice.
Changelog
React-Redux Peer Dep
We'd previously published an RTK build that accepted React-Redux v8 beta as a peer dep (for use with RTK Query). Since React-Redux v8 is out now, we've updated the peer dep to ^8.0.2.
Entity Adapter Updates
Previously, applying updates via createEntityAdapter.updateMany caused sorting order to change. Entities that had the same sorting result should have stayed in the same order relative to each other, but if one of those items had any updates, it would sort to the back of that group. This was due to items being removed from the lookup table and re-added, and since JS engines iterate keys in insertion order, the updated item would now end up compared later than before.
We've reworked the implementation of updateMany to avoid that. This also ended up fixing another issue where multiple update entries targeting the same item ID would only have the first applied.
createSlice Initial State
createSlice now logs an error if initialState is undefined. This is most commonly seen when users misspell initialState. It also has better handling for values that can't be frozen by Immer such as primitives.
RTK Query
Several assorted improvements, including TS types for BaseQuery and checking if the body can actually be safely stringified.
What's Changed
- Add Missing Else to enhanceEndpoints Function by @kinson in https://github.com/reduxjs/redux-toolkit/pull/2386
- Check initial state is draftable before using immer to freeze it. by @EskiMojo14 in https://github.com/reduxjs/redux-toolkit/pull/2378
- Check that body isJsonifiable before stringify by @ShaunDychko in https://github.com/reduxjs/redux-toolkit/pull/2330
- Respect BaseQuery meta types when enhancing by @TamasSzigeti in https://github.com/reduxjs/redux-toolkit/pull/2225
- Throw new error when initial state is undefined by @dannielss in https://github.com/reduxjs/redux-toolkit/pull/2461
- Rewrite
updateManyto ensure stable sorting order by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2464 - Bump React-Redux peer dep by @markerikson in https://github.com/reduxjs/redux-toolkit/commit/3033a33c3dd2ad743f02a44603bc77174599eebc
New Contributors
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.8.2...1.8.3
v1.8.2
This bugfix release fixes a minor issue where calling listenerMiddleware.startListening() multiple times with the same effect callback reference would result in multiple entries being added. The correct behavior is that only the first entry is added, and later attempts to add the same effect callback reference just return the existing entry.
What's Changed
- Add type @remarks for configureStore's middleware by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/2252
- Fix the "map values transpilation" bug, in yet another place by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2351
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.8.1...v1.8.2
v1.8.1
This release updates RTK's peer dependencies to accept React 18 as a valid version. This should fix installation errors caused by NPM's "install all the peer deps and error if they don't match" behavior.
React-Redux and React 18
Note: If you are now using React 18, we strongly recommend using the React-Redux v8 beta instead of v7.x!. v8 has been rewritten internally to work correctly with React 18's Concurrent Rendering capabilities. React-Redux v7 will run and generally work okay with existing code, but may have rendering issues if you start using Concurrent Rendering capabilities in your code.
Now that React 18 is out, we plan to finalize React-Redux v8 and release it live within the next couple weeks. We would really appreciate final feedback on using React-Redux v8 beta with React 18 before we publish the final version.
v1.8.0
This release adds the new "listener" middleware, updates configureStore's types to better handle type inference from middleware that override dispatch return values, and updates our TS support matrix to drop support for TS < 4.1.
Changelog
New "Listener" Side Effects Middleware
RTK has integrated the thunk middleware since the beginning. However, thunks are imperative functions, and do not let you run code in response to dispatched actions. That use case has typically been covered with libraries like redux-saga (which handles side effects with "sagas" based on generator functions), redux-observable (which uses RxJS observables), or custom middleware.
We've added a new "listener" middleware to RTK to cover that use case. The listener middleware is created using createListenerMiddleware(), and lets you define "listener" entries that contain an "effect" callback with additional logic and a way to specify when that callback should run based on dispatched actions or state changes.
Conceptually, you can think of this as being similar to React's useEffect hook, except that it runs logic in response to Redux store updates instead of component props/state updates.
The listener middleware is intended to be a lightweight alternative to more widely used Redux async middleware like sagas and observables. While similar to thunks in level of complexity and concept, it can replicate some common saga usage patterns. We believe that the listener middleware can be used to replace most of the remaining use cases for sagas, but with a fraction of the bundle size and a much simpler API.
Listener effect callbacks have access to dispatch and getState, similar to thunks. The listener also receives a set of async workflow functions like take, condition, pause, fork, and unsubscribe, which allow writing more complex async logic.
Listeners can be defined statically by calling listenerMiddleware.startListening() during setup, or added and removed dynamically at runtime with special dispatch(addListener()) and dispatch(removeListener()) actions.
The API reference is available at:
https://redux-toolkit.js.org/api/createListenerMiddleware
Huge thanks to @FaberVitale for major contributions in refining the middleware API and implementing key functionality.
Basic usage of the listener middleware looks like:
import { configureStore, createListenerMiddleware } from '@​reduxjs/toolkit'
import todosReducer, {
todoAdded,
todoToggled,
todoDeleted,
} from '../features/todos/todosSlice'
// Create the middleware instance and methods
const listenerMiddleware = createListenerMiddleware()
// Add one or more listener entries that look for specific actions.
// They may contain any sync or async logic, similar to thunks.
listenerMiddleware.startListening({
actionCreator: todoAdded,
effect: async (action, listenerApi) => {
// Run whatever additional side-effect-y logic you want here
console.log('Todo added: ', action.payload.text)
// Can cancel other running instances
listenerApi.cancelActiveListeners()
// Run async logic
const data = await fetchData()
// Pause until action dispatched or state changed
if (await listenerApi.condition(matchSomeAction)) {
// Use the listener API methods to dispatch, get state,
// unsubscribe the listener, start child tasks, and more
listenerApi.dispatch(todoAdded('Buy pet food'))
listenerApi.unsubscribe()
}
},
})
const store = configureStore({
reducer: {
todos: todosReducer,
},
// Add the listener middleware to the store.
// NOTE: Since this can receive actions with functions inside,
// it should go before the serializability check middleware
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})
You can use it to write more complex async workflows, including pausing the effect callback until a condition check resolves, and forking "child tasks" to do additional work:
// Track how many times each message was processed by the loop
const receivedMessages = {
a: 0,
b: 0,
c: 0,
}
const eventPollingStarted = createAction('serverPolling/started')
const eventPollingStopped = createAction('serverPolling/stopped')
listenerMiddleware.startListening({
actionCreator: eventPollingStarted,
effect: async (action, listenerApi) => {
// Only allow one instance of this listener to run at a time
listenerApi.unsubscribe()
// Start a child job that will infinitely loop receiving messages
const pollingTask = listenerApi.fork(async (forkApi) => {
try {
while (true) {
// Cancellation-aware pause for a new server message
const serverEvent = await forkApi.pause(pollForEvent())
// Process the message. In this case, just count the times we've seen this message.
if (serverEvent.type in receivedMessages) {
receivedMessages[
serverEvent.type as keyof typeof receivedMessages
]++
}
}
} catch (err) {
if (err instanceof TaskAbortError) {
// could do something here to track that the task was cancelled
}
}
})
// Wait for the "stop polling" action
await listenerApi.condition(eventPollingStopped.match)
pollingTask.cancel()
},
})
configureStore Middleware Type Improvements
Middleware can override the default return value of dispatch. configureStore tries to extract any declared dispatch type overrides from the middleware array, and uses that to alter the type of store.dispatch.
We identified some cases where the type inference wasn't working well enough, and rewrote the type behavior to be more correct.
TypeScript Support Matrix Updates
RTK now requires TS 4.1 or greater to work correctly, and we've dropped 4.0 and earlier from our support matrix.
Other Changes
The internal logic for the serializability middleware has been reorganized to allow skipping checks against actions, while still checking values in the state.
What's Changed
Since most of the implementation work on the middleware was done over the last few months, this list only contains the most recent PRs since 1.7.2. For details on the original use case discussions and the evolution of the middleware API over time, see:
- RTK issue #237: Add an action listener middleware
- RTK PR #547: yet another attempt at an action listener middleware
- RTK discussion #1648: New experimental "action listener middleware" package available
PRs since 1.7.2:
- Rewrite MiddlewareArray and gDM for better Dispatch inference by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2001
- Change listener middleware API name and signature by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2005
- feat(alm): add cancellation message to TaskAbortError, listenerApi.signal & forkApi.signal. by @FaberVitale in https://github.com/reduxjs/redux-toolkit/pull/2023
- [fix][1.8.0-integration][alm]: missing type export by @FaberVitale in https://github.com/reduxjs/redux-toolkit/pull/2026
- [chore][1.8.0-integration][alm]: apply alm breaking API changes to counter-example by @FaberVitale in https://github.com/reduxjs/redux-toolkit/pull/2025
- Reorganize serializable check conditions by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/2000
- fix(alm): prevent zombie listeners caused by forked tasks by @FaberVitale in https://github.com/reduxjs/redux-toolkit/pull/2070
- Integrate the listener middleware into the RTK package by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2072
- fix(alm): cancel forkApi.delay and forkApi.pause if listener is cancelled or completed by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2074
- chore(alm): update counter example to 1.8.0 by @FaberVitale in https://github.com/reduxjs/redux-toolkit/pull/2076
- Enable cancelling active listeners when unsubscribing by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2078
- v1.8.0 integration by @markerikson in https://github.com/reduxjs/redux-toolkit/pull/2024
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.7.2...v1.8.0
v1.7.2
This release fixes a TS types bug with RTK Query generated selectors, makes the RTKQ structural sharing behavior configurable, adds an option to have the serializability middleware ignore all actions, and has several minor bugfixes and enhancements to RTK Query.
Changelog
RTK Query Selector TS Types Fix
Several users had reported that as of 1.7.0 selectors generated via apiSlice.endpoint.select() were failing to compile when used, with TS errors that looked like Type '{}' is missing the following properties from type 'CombinedState<>.
We've fixed the issue, and selectors should now compile correctly when used with TS.
Additional Configuration Options
RTK Query implements a technique called "structural sharing" to preserve existing object references if possible when data for an endpoint is re-fetched. RTKQ recurses over both data structures, and if the contents appear to be the same, keeps the existing values. That helps avoid potential unnecessary re-renders in the UI, because otherwise the entire re-fetched result would be new object references.
However, this update process can potentially take time depending on the size of the response. Endpoints can now be given a structuralSharing option that will turn that off to save on processing time:
const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: "https://example.com" }),
endpoints: (build) => ({
getEveryEntityInADatabase: build.query({
query: () => ({ url: "/i-cant-paginate-data" }),
structuralSharing: false,
}),
}),
});
Additionally, the serializability check middleware can now be customized with an ignoreActions option to exempt all actions from being checked. This is an escape hatch and isn't recommended for most apps:
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoreActions: true,
},
}),
});
Other API Improvements
If an extraArgument was provided to the thunk middleware during store configuration, that value is now passed along to the prepareHeaders() function:
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
thunk: {
extraArgument: { myCustomApiService },
},
}),
});
// ..later on
const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: "https://example.com",
prepareHeaders: async (headers, { getState, extra }) => {
const token = getState().auth.token;
const somethingElse = await extra.myCustomApiService.someMethod();
// do things with somethingElse
return headers;
},
}),
});
The invalidatesTags/providesTags functions now receive the action.meta field as an argument, to help with potentially invalidating based on request/response headers.
Bug Fixes
refetchOnFocus now cleans up cache entries if a focus event is received and there are no active subscriptions, to avoid unnecessary requests.
Active polls are cleaned up when the last component for a given subscription unsubscribes.
The types for builder.addMatcher have been updated to support inference of guards without a type property.
What's Changed
- feat(meta): Passes meta to result description functions [#1904] by @bever1337 in https://github.com/reduxjs/redux-toolkit/pull/1910
- Fix
addMatchertypings by @crcarrick in https://github.com/reduxjs/redux-toolkit/pull/1895 - Pass baseQueryMeta into calculateProvidedBy by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/1926
- Cleanup polls on unsubscribeQueryResult by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/1933
- Add
extratoprepareHeaders, update documentation + tests by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/1922 - fix
reducerPathfor query definitions by @phryneas in https://github.com/reduxjs/redux-toolkit/pull/1977 - Update serialize documentation link by @wuweiweiwu in https://github.com/reduxjs/redux-toolkit/pull/1983
- Refetch should not happen if no active subscribers by @AlexanderArvidsson in https://github.com/reduxjs/redux-toolkit/pull/1974
- Add
ignoreActionsflag to serializable state middleware by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/1984 - RTKQ: configurable
structuralSharingon endpoints/queries/createApi by @msutkowski in https://github.com/reduxjs/redux-toolkit/pull/1954
Full Changelog: https://github.com/reduxjs/redux-toolkit/compare/v1.7.1...v1.7.2
Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
- [ ] If you want to rebase/retry this PR, click this checkbox.
This PR has been generated by Mend Renovate. View repository job log here.
Code Climate has analyzed commit 53cdf0b8 and detected 0 issues on this pull request.
The test coverage on the diff in this pull request is 100.0% (50% is the threshold).
This pull request will bring the total coverage in the repository to 100.0% (0.0% change).
View more on Code Climate.
Codecov Report
Merging #1624 (53cdf0b) into master (edaad53) will not change coverage. The diff coverage is
n/a.
@@ Coverage Diff @@
## master #1624 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 690 690
Branches 175 175
=========================================
Hits 690 690
Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.