@depup/reduxjs__toolkit 2.12.0-depup.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +33 -0
- package/changes.json +18 -0
- package/dist/cjs/index.js +6 -0
- package/dist/cjs/redux-toolkit.development.cjs +2406 -0
- package/dist/cjs/redux-toolkit.development.cjs.map +1 -0
- package/dist/cjs/redux-toolkit.production.min.cjs +3 -0
- package/dist/cjs/redux-toolkit.production.min.cjs.map +1 -0
- package/dist/index.d.mts +2665 -0
- package/dist/index.d.ts +2665 -0
- package/dist/query/cjs/index.js +6 -0
- package/dist/query/cjs/rtk-query.development.cjs +3092 -0
- package/dist/query/cjs/rtk-query.development.cjs.map +1 -0
- package/dist/query/cjs/rtk-query.production.min.cjs +2 -0
- package/dist/query/cjs/rtk-query.production.min.cjs.map +1 -0
- package/dist/query/index.d.mts +3066 -0
- package/dist/query/index.d.ts +3066 -0
- package/dist/query/react/cjs/index.js +6 -0
- package/dist/query/react/cjs/rtk-query-react.development.cjs +748 -0
- package/dist/query/react/cjs/rtk-query-react.development.cjs.map +1 -0
- package/dist/query/react/cjs/rtk-query-react.production.min.cjs +2 -0
- package/dist/query/react/cjs/rtk-query-react.production.min.cjs.map +1 -0
- package/dist/query/react/index.d.mts +1009 -0
- package/dist/query/react/index.d.ts +1009 -0
- package/dist/query/react/rtk-query-react.browser.mjs +2 -0
- package/dist/query/react/rtk-query-react.browser.mjs.map +1 -0
- package/dist/query/react/rtk-query-react.legacy-esm.js +740 -0
- package/dist/query/react/rtk-query-react.legacy-esm.js.map +1 -0
- package/dist/query/react/rtk-query-react.modern.mjs +705 -0
- package/dist/query/react/rtk-query-react.modern.mjs.map +1 -0
- package/dist/query/rtk-query.browser.mjs +2 -0
- package/dist/query/rtk-query.browser.mjs.map +1 -0
- package/dist/query/rtk-query.legacy-esm.js +3117 -0
- package/dist/query/rtk-query.legacy-esm.js.map +1 -0
- package/dist/query/rtk-query.modern.mjs +3052 -0
- package/dist/query/rtk-query.modern.mjs.map +1 -0
- package/dist/react/cjs/index.js +6 -0
- package/dist/react/cjs/redux-toolkit-react.development.cjs +55 -0
- package/dist/react/cjs/redux-toolkit-react.development.cjs.map +1 -0
- package/dist/react/cjs/redux-toolkit-react.production.min.cjs +2 -0
- package/dist/react/cjs/redux-toolkit-react.production.min.cjs.map +1 -0
- package/dist/react/index.d.mts +22 -0
- package/dist/react/index.d.ts +22 -0
- package/dist/react/redux-toolkit-react.browser.mjs +2 -0
- package/dist/react/redux-toolkit-react.browser.mjs.map +1 -0
- package/dist/react/redux-toolkit-react.legacy-esm.js +47 -0
- package/dist/react/redux-toolkit-react.legacy-esm.js.map +1 -0
- package/dist/react/redux-toolkit-react.modern.mjs +28 -0
- package/dist/react/redux-toolkit-react.modern.mjs.map +1 -0
- package/dist/redux-toolkit.browser.mjs +3 -0
- package/dist/redux-toolkit.browser.mjs.map +1 -0
- package/dist/redux-toolkit.legacy-esm.js +2351 -0
- package/dist/redux-toolkit.legacy-esm.js.map +1 -0
- package/dist/redux-toolkit.modern.mjs +2330 -0
- package/dist/redux-toolkit.modern.mjs.map +1 -0
- package/dist/uncheckedindexed.ts +16 -0
- package/package.json +310 -0
- package/query/package.json +13 -0
- package/query/react/package.json +13 -0
- package/react/package.json +13 -0
- package/skills/build-modern-redux-apps/modern-redux/SKILL.md +304 -0
- package/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +53 -0
- package/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +264 -0
- package/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +269 -0
- package/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +226 -0
- package/skills/manage-server-data/adopt-rtk-query/SKILL.md +385 -0
- package/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md +36 -0
- package/skills/model-redux-state/build-slices-and-selectors/SKILL.md +364 -0
- package/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md +59 -0
- package/skills/model-redux-state/design-state-ownership/SKILL.md +322 -0
- package/skills/model-redux-state/design-state-ownership/references/state-ownership.md +28 -0
- package/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +271 -0
- package/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +34 -0
- package/src/actionCreatorInvariantMiddleware.ts +34 -0
- package/src/autoBatchEnhancer.ts +146 -0
- package/src/combineSlices.ts +487 -0
- package/src/configureStore.ts +248 -0
- package/src/createAction.ts +324 -0
- package/src/createAsyncThunk.ts +791 -0
- package/src/createDraftSafeSelector.ts +30 -0
- package/src/createReducer.ts +217 -0
- package/src/createSlice.ts +1079 -0
- package/src/devtoolsExtension.ts +241 -0
- package/src/dynamicMiddleware/index.ts +93 -0
- package/src/dynamicMiddleware/react/index.ts +101 -0
- package/src/dynamicMiddleware/types.ts +82 -0
- package/src/entities/create_adapter.ts +47 -0
- package/src/entities/entity_state.ts +38 -0
- package/src/entities/index.ts +8 -0
- package/src/entities/models.ts +198 -0
- package/src/entities/sorted_state_adapter.ts +266 -0
- package/src/entities/state_adapter.ts +58 -0
- package/src/entities/state_selectors.ts +73 -0
- package/src/entities/unsorted_state_adapter.ts +204 -0
- package/src/entities/utils.ts +68 -0
- package/src/formatProdErrorMessage.ts +13 -0
- package/src/getDefaultEnhancers.ts +31 -0
- package/src/getDefaultMiddleware.ts +113 -0
- package/src/immerImports.ts +7 -0
- package/src/immutableStateInvariantMiddleware.ts +274 -0
- package/src/index.ts +213 -0
- package/src/listenerMiddleware/exceptions.ts +20 -0
- package/src/listenerMiddleware/index.ts +562 -0
- package/src/listenerMiddleware/task.ts +100 -0
- package/src/listenerMiddleware/types.ts +886 -0
- package/src/listenerMiddleware/utils.ts +30 -0
- package/src/mapBuilders.ts +298 -0
- package/src/matchers.ts +365 -0
- package/src/nanoid.ts +20 -0
- package/src/query/HandledError.ts +6 -0
- package/src/query/apiTypes.ts +120 -0
- package/src/query/baseQueryTypes.ts +101 -0
- package/src/query/core/apiState.ts +377 -0
- package/src/query/core/buildInitiate.ts +596 -0
- package/src/query/core/buildMiddleware/batchActions.ts +207 -0
- package/src/query/core/buildMiddleware/cacheCollection.ts +204 -0
- package/src/query/core/buildMiddleware/cacheLifecycle.ts +379 -0
- package/src/query/core/buildMiddleware/devMiddleware.ts +34 -0
- package/src/query/core/buildMiddleware/index.ts +162 -0
- package/src/query/core/buildMiddleware/invalidationByTags.ts +139 -0
- package/src/query/core/buildMiddleware/polling.ts +187 -0
- package/src/query/core/buildMiddleware/queryLifecycle.ts +508 -0
- package/src/query/core/buildMiddleware/types.ts +173 -0
- package/src/query/core/buildMiddleware/windowEventHandling.ts +64 -0
- package/src/query/core/buildSelectors.ts +413 -0
- package/src/query/core/buildSlice.ts +735 -0
- package/src/query/core/buildThunks.ts +1124 -0
- package/src/query/core/index.ts +58 -0
- package/src/query/core/module.ts +727 -0
- package/src/query/core/rtkImports.ts +24 -0
- package/src/query/core/setupListeners.ts +118 -0
- package/src/query/createApi.ts +506 -0
- package/src/query/defaultSerializeQueryArgs.ts +52 -0
- package/src/query/endpointDefinitions.ts +1717 -0
- package/src/query/fakeBaseQuery.ts +21 -0
- package/src/query/fetchBaseQuery.ts +385 -0
- package/src/query/index.ts +105 -0
- package/src/query/react/ApiProvider.tsx +69 -0
- package/src/query/react/buildHooks.ts +2297 -0
- package/src/query/react/constants.ts +2 -0
- package/src/query/react/index.ts +45 -0
- package/src/query/react/module.ts +275 -0
- package/src/query/react/namedHooks.ts +59 -0
- package/src/query/react/reactImports.ts +10 -0
- package/src/query/react/reactReduxImports.ts +1 -0
- package/src/query/react/rtkqImports.ts +8 -0
- package/src/query/react/useSerializedStableValue.ts +17 -0
- package/src/query/react/useShallowStableValue.ts +13 -0
- package/src/query/retry.ts +233 -0
- package/src/query/standardSchema.ts +35 -0
- package/src/query/tsHelpers.ts +48 -0
- package/src/query/utils/capitalize.ts +3 -0
- package/src/query/utils/copyWithStructuralSharing.ts +27 -0
- package/src/query/utils/countObjectKeys.ts +14 -0
- package/src/query/utils/filterMap.ts +27 -0
- package/src/query/utils/getCurrent.ts +6 -0
- package/src/query/utils/getOrInsert.ts +41 -0
- package/src/query/utils/immerImports.ts +9 -0
- package/src/query/utils/index.ts +11 -0
- package/src/query/utils/isAbsoluteUrl.ts +9 -0
- package/src/query/utils/isDocumentVisible.ts +12 -0
- package/src/query/utils/isNotNullish.ts +7 -0
- package/src/query/utils/isOnline.ts +12 -0
- package/src/query/utils/isValidUrl.ts +9 -0
- package/src/query/utils/joinUrls.ts +26 -0
- package/src/query/utils/signals.ts +33 -0
- package/src/react/index.ts +7 -0
- package/src/reduxImports.ts +8 -0
- package/src/reselectImports.ts +1 -0
- package/src/serializableStateInvariantMiddleware.ts +285 -0
- package/src/tsHelpers.ts +214 -0
- package/src/uncheckedindexed.ts +16 -0
- package/src/utils.ts +125 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Store Lifetime
|
|
2
|
+
|
|
3
|
+
## Decision table
|
|
4
|
+
|
|
5
|
+
| Environment | Default store shape | Why |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| Client-only SPA | One module-level singleton store | There is one browser session and no cross-request leakage risk. |
|
|
8
|
+
| SSR-heavy React app | `makeStore()` plus provider-local state | Each request needs its own store instance, but that instance must stay stable across client renders. |
|
|
9
|
+
| Non-React integration code | Direct store access can be acceptable | This is outside the React context boundary and should stay out of UI components. |
|
|
10
|
+
|
|
11
|
+
## SPA pattern
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { configureStore } from '@reduxjs/toolkit'
|
|
15
|
+
import { postsSlice } from '../features/posts/postsSlice'
|
|
16
|
+
|
|
17
|
+
export const store = configureStore({
|
|
18
|
+
reducer: {
|
|
19
|
+
posts: postsSlice.reducer,
|
|
20
|
+
},
|
|
21
|
+
})
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Use this for classic browser SPAs.
|
|
25
|
+
|
|
26
|
+
## SSR-heavy React pattern
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
// file: src/lib/store.ts
|
|
30
|
+
import { configureStore } from '@reduxjs/toolkit'
|
|
31
|
+
import { postsSlice } from '../features/posts/postsSlice'
|
|
32
|
+
|
|
33
|
+
export const makeStore = () =>
|
|
34
|
+
configureStore({
|
|
35
|
+
reducer: {
|
|
36
|
+
posts: postsSlice.reducer,
|
|
37
|
+
},
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
// file: src/app/StoreProvider.tsx
|
|
41
|
+
'use client'
|
|
42
|
+
|
|
43
|
+
import { useState, type ReactNode } from 'react'
|
|
44
|
+
import { Provider } from 'react-redux'
|
|
45
|
+
import { makeStore } from '../lib/store'
|
|
46
|
+
|
|
47
|
+
export function StoreProvider({ children }: { children: ReactNode }) {
|
|
48
|
+
const [store] = useState(makeStore)
|
|
49
|
+
return <Provider store={store}>{children}</Provider>
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Create the store per request, then keep it stable inside the provider component.
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: build-modern-redux-apps/redux-dataflow
|
|
3
|
+
description: >
|
|
4
|
+
Use this when you need the Redux event -> reducer -> selector -> render loop,
|
|
5
|
+
event-style actions, reducer-owned state transitions, derived data, or a
|
|
6
|
+
debugging model for Redux Toolkit apps.
|
|
7
|
+
type: core
|
|
8
|
+
library: "@reduxjs/toolkit"
|
|
9
|
+
library_version: "2.11.2"
|
|
10
|
+
sources:
|
|
11
|
+
- "reduxjs/redux:docs/tutorials/fundamentals/part-2-concepts-data-flow.md"
|
|
12
|
+
- "reduxjs/redux:docs/tutorials/essentials/part-3-data-flow.md"
|
|
13
|
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Redux Dataflow
|
|
17
|
+
|
|
18
|
+
## Setup
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { configureStore, createSelector, createSlice } from '@reduxjs/toolkit'
|
|
22
|
+
|
|
23
|
+
const postsSlice = createSlice({
|
|
24
|
+
name: 'posts',
|
|
25
|
+
initialState: {
|
|
26
|
+
items: [] as { id: string; title: string; published: boolean }[],
|
|
27
|
+
filter: 'all' as 'all' | 'published',
|
|
28
|
+
},
|
|
29
|
+
reducers: {
|
|
30
|
+
postAdded(state, action: { payload: { id: string; title: string } }) {
|
|
31
|
+
state.items.push({ ...action.payload, published: false })
|
|
32
|
+
},
|
|
33
|
+
postPublished(state, action: { payload: { id: string } }) {
|
|
34
|
+
const post = state.items.find((item) => item.id === action.payload.id)
|
|
35
|
+
if (post) {
|
|
36
|
+
post.published = true
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
filterChanged(state, action: { payload: 'all' | 'published' }) {
|
|
40
|
+
state.filter = action.payload
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
const store = configureStore({
|
|
46
|
+
reducer: {
|
|
47
|
+
posts: postsSlice.reducer,
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
type RootState = ReturnType<typeof store.getState>
|
|
52
|
+
|
|
53
|
+
const selectPostsState = (state: RootState) => state.posts
|
|
54
|
+
const selectVisiblePosts = createSelector([selectPostsState], (postsState) =>
|
|
55
|
+
postsState.filter === 'all'
|
|
56
|
+
? postsState.items
|
|
57
|
+
: postsState.items.filter((post) => post.published),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
store.dispatch(postsSlice.actions.postAdded({ id: 'p1', title: 'Draft' }))
|
|
61
|
+
store.dispatch(postsSlice.actions.postPublished({ id: 'p1' }))
|
|
62
|
+
|
|
63
|
+
const visiblePosts = selectVisiblePosts(store.getState())
|
|
64
|
+
console.log(visiblePosts)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Core Patterns
|
|
68
|
+
|
|
69
|
+
### Dispatch events, not setters
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
const postsSlice = createSlice({
|
|
73
|
+
name: 'posts',
|
|
74
|
+
initialState: [] as { id: string; title: string }[],
|
|
75
|
+
reducers: {
|
|
76
|
+
postAdded(state, action: { payload: { id: string; title: string } }) {
|
|
77
|
+
state.push(action.payload)
|
|
78
|
+
},
|
|
79
|
+
postRemoved(state, action: { payload: { id: string } }) {
|
|
80
|
+
return state.filter((post) => post.id !== action.payload.id)
|
|
81
|
+
},
|
|
82
|
+
postUpdated(
|
|
83
|
+
state,
|
|
84
|
+
action: { payload: { id: string; changes: Partial<{ title: string }> } },
|
|
85
|
+
) {
|
|
86
|
+
const post = state.find((item) => item.id === action.payload.id)
|
|
87
|
+
if (post && action.payload.changes.title) {
|
|
88
|
+
post.title = action.payload.changes.title
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
postsSlice.actions.postAdded({ id: 'p1', title: 'Draft' })
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Event-style actions explain what happened in the UI instead of hiding the transition behind a generic setter.
|
|
98
|
+
|
|
99
|
+
### Let reducers combine old store data with new outside data
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
|
|
103
|
+
|
|
104
|
+
const postsAdapter = createEntityAdapter<{ id: string; title: string }>()
|
|
105
|
+
|
|
106
|
+
const postsSlice = createSlice({
|
|
107
|
+
name: 'posts',
|
|
108
|
+
initialState: postsAdapter.getInitialState(),
|
|
109
|
+
reducers: {
|
|
110
|
+
postsReceived(state, action: { payload: { id: string; title: string }[] }) {
|
|
111
|
+
postsAdapter.upsertMany(state, action.payload)
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
const incomingPosts = [
|
|
117
|
+
{ id: 'p1', title: 'Draft' },
|
|
118
|
+
{ id: 'p2', title: 'Published' },
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
postsSlice.actions.postsReceived(incomingPosts)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
If a transition mixes current store state with new external data, dispatch the new external data and let the reducer own the merge.
|
|
125
|
+
|
|
126
|
+
### Derive values with selectors instead of storing duplicates
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { createSelector } from '@reduxjs/toolkit'
|
|
130
|
+
|
|
131
|
+
const selectPosts = (state: RootState) => state.posts.items
|
|
132
|
+
const selectFilter = (state: RootState) => state.posts.filter
|
|
133
|
+
|
|
134
|
+
export const selectVisiblePosts = createSelector(
|
|
135
|
+
[selectPosts, selectFilter],
|
|
136
|
+
(posts, filter) =>
|
|
137
|
+
filter === 'all'
|
|
138
|
+
? posts
|
|
139
|
+
: posts.filter((post) => post.published),
|
|
140
|
+
)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Selectors keep a single source of truth in state while still exposing the shapes the UI needs.
|
|
144
|
+
|
|
145
|
+
## Common Mistakes
|
|
146
|
+
|
|
147
|
+
### CRITICAL Mutating selected state outside reducers
|
|
148
|
+
|
|
149
|
+
Wrong:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const post = selectPostById(store.getState(), 'p1')
|
|
153
|
+
|
|
154
|
+
if (post) {
|
|
155
|
+
post.title = 'Changed in place'
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Correct:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
store.dispatch(postUpdated({ id: 'p1', changes: { title: 'Changed in place' } }))
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Objects read from the store are still store state; mutating them outside reducers breaks immutability and stale-render assumptions.
|
|
166
|
+
|
|
167
|
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
|
168
|
+
|
|
169
|
+
### HIGH Using setter-style actions instead of event-style actions
|
|
170
|
+
|
|
171
|
+
Wrong:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
const nextPosts = [...selectPosts(store.getState()), { id: 'p2', title: 'Write docs' }]
|
|
175
|
+
store.dispatch(setPosts(nextPosts))
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Correct:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
store.dispatch(postAdded({ id: 'p2', title: 'Write docs' }))
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Actions should describe events, not ask reducers to blindly replace state with a precomputed value.
|
|
185
|
+
|
|
186
|
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
|
187
|
+
|
|
188
|
+
### HIGH Combining store state before dispatch
|
|
189
|
+
|
|
190
|
+
Wrong:
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
const currentPosts = selectPosts(store.getState())
|
|
194
|
+
const mergedPosts = [
|
|
195
|
+
...currentPosts.filter(
|
|
196
|
+
(currentPost) =>
|
|
197
|
+
!incomingPosts.some((incomingPost) => incomingPost.id === currentPost.id),
|
|
198
|
+
),
|
|
199
|
+
...incomingPosts,
|
|
200
|
+
]
|
|
201
|
+
|
|
202
|
+
store.dispatch(postsReplaced(mergedPosts))
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Correct:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
store.dispatch(postsReceived(incomingPosts))
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
If the next state depends on current store state, the reducer should own that combination logic; only authoritative external snapshots should replace state wholesale.
|
|
212
|
+
|
|
213
|
+
Source: maintainer interview
|
|
214
|
+
|
|
215
|
+
### HIGH Ignoring current state in async reducers
|
|
216
|
+
|
|
217
|
+
Wrong:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
builder.addCase(fetchPosts.fulfilled, (state, action) => {
|
|
221
|
+
state.status = 'succeeded'
|
|
222
|
+
state.items = action.payload
|
|
223
|
+
})
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Correct:
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
builder.addCase(fetchPosts.fulfilled, (state, action) => {
|
|
230
|
+
if (state.status === 'pending') {
|
|
231
|
+
state.status = 'succeeded'
|
|
232
|
+
state.items = action.payload
|
|
233
|
+
}
|
|
234
|
+
})
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Reducers that treat every lifecycle action as valid can move the slice into impossible states or let stale requests win.
|
|
238
|
+
|
|
239
|
+
Source: reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md
|
|
240
|
+
|
|
241
|
+
### MEDIUM Storing derived values in state
|
|
242
|
+
|
|
243
|
+
Wrong:
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
const initialState = {
|
|
247
|
+
items: [] as Post[],
|
|
248
|
+
visiblePosts: [] as Post[],
|
|
249
|
+
}
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
Correct:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
const selectVisiblePosts = createSelector(
|
|
256
|
+
[selectPosts, selectFilter],
|
|
257
|
+
(posts, filter) =>
|
|
258
|
+
filter === 'all' ? posts : posts.filter((post) => post.published),
|
|
259
|
+
)
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Derived values drift out of sync quickly; keep the raw state and derive the view shape.
|
|
263
|
+
|
|
264
|
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps
|
|
3
|
+
description: >
|
|
4
|
+
Use this when debugging duplicate requests, stale cache behavior, broad
|
|
5
|
+
subscriptions, selector churn, serializability warnings, or other Redux
|
|
6
|
+
Toolkit and RTK Query bugs. Covers a practical event -> reducer -> selector ->
|
|
7
|
+
render debugging loop plus RTK Query cache interpretation.
|
|
8
|
+
type: lifecycle
|
|
9
|
+
library: "@reduxjs/toolkit"
|
|
10
|
+
library_version: "2.11.2"
|
|
11
|
+
requires:
|
|
12
|
+
- build-modern-redux-apps/redux-dataflow
|
|
13
|
+
sources:
|
|
14
|
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
|
15
|
+
- "reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md"
|
|
16
|
+
- "reduxjs/redux:docs/tutorials/essentials/part-8-rtk-query-advanced.md"
|
|
17
|
+
- "reduxjs/redux-toolkit:docs/usage/usage-guide.md"
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
# Debug Redux Toolkit Apps
|
|
21
|
+
|
|
22
|
+
## Setup
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit'
|
|
26
|
+
|
|
27
|
+
type Post = { id: string; title: string }
|
|
28
|
+
|
|
29
|
+
export const fetchPosts = createAsyncThunk(
|
|
30
|
+
'posts/fetchPosts',
|
|
31
|
+
async () => {
|
|
32
|
+
const response = await fetch('/api/posts')
|
|
33
|
+
return (await response.json()) as Post[]
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
condition(_arg, { getState }) {
|
|
37
|
+
const state = getState() as RootState
|
|
38
|
+
return state.posts.status === 'idle'
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
const postsSlice = createSlice({
|
|
44
|
+
name: 'posts',
|
|
45
|
+
initialState: {
|
|
46
|
+
items: [] as Post[],
|
|
47
|
+
status: 'idle' as 'idle' | 'pending' | 'succeeded' | 'failed',
|
|
48
|
+
},
|
|
49
|
+
reducers: {},
|
|
50
|
+
extraReducers: (builder) => {
|
|
51
|
+
builder
|
|
52
|
+
.addCase(fetchPosts.pending, (state) => {
|
|
53
|
+
state.status = 'pending'
|
|
54
|
+
})
|
|
55
|
+
.addCase(fetchPosts.fulfilled, (state, action) => {
|
|
56
|
+
state.status = 'succeeded'
|
|
57
|
+
state.items = action.payload
|
|
58
|
+
})
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
export const store = configureStore({
|
|
63
|
+
reducer: {
|
|
64
|
+
posts: postsSlice.reducer,
|
|
65
|
+
},
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
type RootState = ReturnType<typeof store.getState>
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Core Patterns
|
|
72
|
+
|
|
73
|
+
### Debug in order: action -> reducer -> selector -> render
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
const selectPosts = (state: RootState) => state.posts.items
|
|
77
|
+
const selectPostsStatus = (state: RootState) => state.posts.status
|
|
78
|
+
|
|
79
|
+
store.dispatch(fetchPosts())
|
|
80
|
+
|
|
81
|
+
console.log(selectPostsStatus(store.getState()))
|
|
82
|
+
console.log(selectPosts(store.getState()))
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
If a component looks wrong, first verify the action fired, then the reducer state, then the selector result, then the render boundary.
|
|
86
|
+
|
|
87
|
+
### Narrow subscriptions at the usage site
|
|
88
|
+
|
|
89
|
+
```tsx
|
|
90
|
+
import { useAppSelector } from '../../app/hooks'
|
|
91
|
+
|
|
92
|
+
export function PostsList() {
|
|
93
|
+
const posts = useAppSelector((state) => state.posts.items)
|
|
94
|
+
const status = useAppSelector((state) => state.posts.status)
|
|
95
|
+
|
|
96
|
+
return (
|
|
97
|
+
<div>
|
|
98
|
+
<div>{status}</div>
|
|
99
|
+
<div>{posts.length}</div>
|
|
100
|
+
</div>
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
React-Redux behaves best when components select only the values they render and do it as close to usage as possible.
|
|
106
|
+
|
|
107
|
+
### Interpret RTK Query invalidation correctly
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
|
111
|
+
|
|
112
|
+
type Post = { id: string; title: string }
|
|
113
|
+
|
|
114
|
+
const api = createApi({
|
|
115
|
+
reducerPath: 'api',
|
|
116
|
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
|
117
|
+
tagTypes: ['Post'],
|
|
118
|
+
endpoints: (build) => ({
|
|
119
|
+
getPosts: build.query<Post[], void>({
|
|
120
|
+
query: () => 'posts',
|
|
121
|
+
providesTags: ['Post'],
|
|
122
|
+
}),
|
|
123
|
+
updatePost: build.mutation<Post, Pick<Post, 'id' | 'title'>>({
|
|
124
|
+
query: ({ id, title }) => ({
|
|
125
|
+
url: `posts/${id}`,
|
|
126
|
+
method: 'PATCH',
|
|
127
|
+
body: { title },
|
|
128
|
+
}),
|
|
129
|
+
invalidatesTags: ['Post'],
|
|
130
|
+
}),
|
|
131
|
+
}),
|
|
132
|
+
})
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
If invalidation did not visibly refetch, check whether anything was still subscribed to that cache entry.
|
|
136
|
+
|
|
137
|
+
## Common Mistakes
|
|
138
|
+
|
|
139
|
+
### HIGH Dispatching fetch thunks from effects without a thunk-level guard
|
|
140
|
+
|
|
141
|
+
Wrong:
|
|
142
|
+
|
|
143
|
+
```tsx
|
|
144
|
+
import { useEffect } from 'react'
|
|
145
|
+
import { useAppDispatch, useAppSelector } from '../../app/hooks'
|
|
146
|
+
|
|
147
|
+
function PostsPage() {
|
|
148
|
+
const dispatch = useAppDispatch()
|
|
149
|
+
const postStatus = useAppSelector((state) => state.posts.status)
|
|
150
|
+
|
|
151
|
+
useEffect(() => {
|
|
152
|
+
if (postStatus === 'idle') {
|
|
153
|
+
dispatch(fetchPosts())
|
|
154
|
+
}
|
|
155
|
+
}, [dispatch, postStatus])
|
|
156
|
+
|
|
157
|
+
return null
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Correct:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
export const fetchPosts = createAsyncThunk(
|
|
165
|
+
'posts/fetchPosts',
|
|
166
|
+
async () => {
|
|
167
|
+
const response = await fetch('/api/posts')
|
|
168
|
+
return (await response.json()) as Post[]
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
condition(_arg, { getState }) {
|
|
172
|
+
const state = getState() as RootState
|
|
173
|
+
return state.posts.status === 'idle'
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
React StrictMode can run effects twice in development, so the guard belongs in the thunk as well as the component.
|
|
180
|
+
|
|
181
|
+
Source: reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md
|
|
182
|
+
|
|
183
|
+
### HIGH Ignoring serializable-state warnings
|
|
184
|
+
|
|
185
|
+
Wrong:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
const initialState = {
|
|
189
|
+
lastSeen: new Date(),
|
|
190
|
+
pendingIds: new Set<string>(),
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Correct:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
const initialState = {
|
|
198
|
+
lastSeenIso: new Date().toISOString(),
|
|
199
|
+
pendingIds: [] as string[],
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Non-serializable values break DevTools, replay, persistence, and equality assumptions in subtle ways.
|
|
204
|
+
|
|
205
|
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
|
206
|
+
|
|
207
|
+
### HIGH Selecting broad state in parents and threading props
|
|
208
|
+
|
|
209
|
+
Wrong:
|
|
210
|
+
|
|
211
|
+
```tsx
|
|
212
|
+
import { useAppSelector } from '../../app/hooks'
|
|
213
|
+
|
|
214
|
+
function PostsPage() {
|
|
215
|
+
const postsState = useAppSelector((state) => state.posts)
|
|
216
|
+
return <PostsList items={postsState.items} status={postsState.status} />
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Correct:
|
|
221
|
+
|
|
222
|
+
```tsx
|
|
223
|
+
import { useAppSelector } from '../../app/hooks'
|
|
224
|
+
|
|
225
|
+
function PostsList() {
|
|
226
|
+
const items = useAppSelector((state) => state.posts.items)
|
|
227
|
+
const status = useAppSelector((state) => state.posts.status)
|
|
228
|
+
return (
|
|
229
|
+
<div>
|
|
230
|
+
<div>{status}</div>
|
|
231
|
+
<div>{items.length}</div>
|
|
232
|
+
</div>
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Selecting whole slices high in the tree widens the subscription surface and pushes rerenders through props.
|
|
238
|
+
|
|
239
|
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
|
240
|
+
|
|
241
|
+
### MEDIUM Returning unstable objects from query selection logic
|
|
242
|
+
|
|
243
|
+
Wrong:
|
|
244
|
+
|
|
245
|
+
```tsx
|
|
246
|
+
import { api } from '../../services/api'
|
|
247
|
+
|
|
248
|
+
const result = api.useGetPostsQuery(undefined, {
|
|
249
|
+
selectFromResult: ({ data = [] }) => ({
|
|
250
|
+
posts: [...data],
|
|
251
|
+
}),
|
|
252
|
+
})
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Correct:
|
|
256
|
+
|
|
257
|
+
```tsx
|
|
258
|
+
import { api } from '../../services/api'
|
|
259
|
+
|
|
260
|
+
const result = api.useGetPostsQuery(undefined, {
|
|
261
|
+
selectFromResult: ({ data = [] }) => ({
|
|
262
|
+
posts: data,
|
|
263
|
+
}),
|
|
264
|
+
})
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
New object and array references defeat memoization and make components rerender even when the underlying cached data did not change.
|
|
268
|
+
|
|
269
|
+
Source: reduxjs/redux:docs/tutorials/essentials/part-8-rtk-query-advanced.md
|