Upload folder using huggingface_hub (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- node_modules/@reduxjs/toolkit/LICENSE +21 -0
- node_modules/@reduxjs/toolkit/README.md +112 -0
- node_modules/@reduxjs/toolkit/package.json +285 -0
- node_modules/@reduxjs/toolkit/query/package.json +13 -0
- node_modules/@reduxjs/toolkit/query/react/package.json +13 -0
- node_modules/@reduxjs/toolkit/react/package.json +13 -0
- node_modules/@reduxjs/toolkit/skills/build-modern-redux-apps/modern-redux/SKILL.md +304 -0
- node_modules/@reduxjs/toolkit/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +53 -0
- node_modules/@reduxjs/toolkit/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +264 -0
- node_modules/@reduxjs/toolkit/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +269 -0
- node_modules/@reduxjs/toolkit/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +226 -0
- node_modules/@reduxjs/toolkit/skills/manage-server-data/adopt-rtk-query/SKILL.md +385 -0
- node_modules/@reduxjs/toolkit/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md +36 -0
- node_modules/@reduxjs/toolkit/skills/model-redux-state/build-slices-and-selectors/SKILL.md +364 -0
- node_modules/@reduxjs/toolkit/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md +59 -0
- node_modules/@reduxjs/toolkit/skills/model-redux-state/design-state-ownership/SKILL.md +322 -0
- node_modules/@reduxjs/toolkit/skills/model-redux-state/design-state-ownership/references/state-ownership.md +28 -0
- node_modules/@reduxjs/toolkit/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +271 -0
- node_modules/@reduxjs/toolkit/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +34 -0
- node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts +34 -0
- node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts +146 -0
- node_modules/@reduxjs/toolkit/src/combineSlices.ts +487 -0
- node_modules/@reduxjs/toolkit/src/configureStore.ts +248 -0
- node_modules/@reduxjs/toolkit/src/createAction.ts +324 -0
- node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts +791 -0
- node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts +30 -0
- node_modules/@reduxjs/toolkit/src/createReducer.ts +217 -0
- node_modules/@reduxjs/toolkit/src/createSlice.ts +1079 -0
- node_modules/@reduxjs/toolkit/src/devtoolsExtension.ts +241 -0
- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts +93 -0
- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts +101 -0
- node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts +82 -0
- node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts +47 -0
- node_modules/@reduxjs/toolkit/src/entities/entity_state.ts +38 -0
- node_modules/@reduxjs/toolkit/src/entities/index.ts +8 -0
- node_modules/@reduxjs/toolkit/src/entities/models.ts +198 -0
- node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts +266 -0
- node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts +58 -0
- node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts +73 -0
- node_modules/@reduxjs/toolkit/src/entities/unsorted_state_adapter.ts +204 -0
- node_modules/@reduxjs/toolkit/src/entities/utils.ts +68 -0
- node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts +13 -0
- node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts +31 -0
- node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts +113 -0
- node_modules/@reduxjs/toolkit/src/immerImports.ts +7 -0
- node_modules/@reduxjs/toolkit/src/immutableStateInvariantMiddleware.ts +274 -0
- node_modules/@reduxjs/toolkit/src/index.ts +213 -0
- node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts +20 -0
- node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts +562 -0
.gitattributes
CHANGED
|
@@ -34,3 +34,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
node_modules/@esbuild/win32-x64/esbuild.exe filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
node_modules/@esbuild/win32-x64/esbuild.exe filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
node_modules/@rollup/rollup-win32-x64-gnu/rollup.win32-x64-gnu.node filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node filter=lfs diff=lfs merge=lfs -text
|
node_modules/@reduxjs/toolkit/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2018 Mark Erikson
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
node_modules/@reduxjs/toolkit/README.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Redux Toolkit
|
| 2 |
+
|
| 3 |
+

|
| 4 |
+
[](https://www.npmjs.com/package/@reduxjs/toolkit)
|
| 5 |
+
[](https://www.npmjs.com/package/@reduxjs/toolkit)
|
| 6 |
+
|
| 7 |
+
**The official, opinionated, batteries-included toolset for efficient Redux development**
|
| 8 |
+
|
| 9 |
+
## Installation
|
| 10 |
+
|
| 11 |
+
### Create a React Redux App
|
| 12 |
+
|
| 13 |
+
The recommended way to start new apps with React and Redux Toolkit is by using [our official Redux Toolkit + TS template for Vite](https://github.com/reduxjs/redux-templates), or by creating a new Next.js project using [Next's `with-redux` template](https://github.com/vercel/next.js/tree/canary/examples/with-redux).
|
| 14 |
+
|
| 15 |
+
Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
# Vite with our Redux+TS template
|
| 19 |
+
# (using the `degit` tool to clone and extract the template)
|
| 20 |
+
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
|
| 21 |
+
|
| 22 |
+
# Next.js using the `with-redux` template
|
| 23 |
+
npx create-next-app --example with-redux my-app
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:
|
| 27 |
+
|
| 28 |
+
- https://github.com/rahsheen/react-native-template-redux-typescript
|
| 29 |
+
- https://github.com/rahsheen/expo-template-redux-typescript
|
| 30 |
+
|
| 31 |
+
### An Existing App
|
| 32 |
+
|
| 33 |
+
Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
# NPM
|
| 37 |
+
npm install @reduxjs/toolkit
|
| 38 |
+
|
| 39 |
+
# Yarn
|
| 40 |
+
yarn add @reduxjs/toolkit
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
If you use an AI agent, run `npx @tanstack/intent@latest install` to install agent skills.
|
| 44 |
+
|
| 45 |
+
The package includes a precompiled ESM build that can be used as a [`<script type="module">` tag](https://unpkg.com/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs) directly in the browser.
|
| 46 |
+
|
| 47 |
+
## Documentation
|
| 48 |
+
|
| 49 |
+
The Redux Toolkit docs are available at **https://redux-toolkit.js.org**, including API references and usage guides for all of the APIs included in Redux Toolkit.
|
| 50 |
+
|
| 51 |
+
The Redux core docs at https://redux.js.org includes the full Redux tutorials, as well usage guides on general Redux patterns.
|
| 52 |
+
|
| 53 |
+
## Purpose
|
| 54 |
+
|
| 55 |
+
The **Redux Toolkit** package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:
|
| 56 |
+
|
| 57 |
+
- "Configuring a Redux store is too complicated"
|
| 58 |
+
- "I have to add a lot of packages to get Redux to do anything useful"
|
| 59 |
+
- "Redux requires too much boilerplate code"
|
| 60 |
+
|
| 61 |
+
We can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app), we can try to provide some tools that abstract over the setup process and handle the most common use cases, as well as include some useful utilities that will let the user simplify their application code.
|
| 62 |
+
|
| 63 |
+
Because of that, this package is deliberately limited in scope. It does _not_ address concepts like "reusable encapsulated Redux modules", folder or file structures, managing entity relationships in the store, and so on.
|
| 64 |
+
|
| 65 |
+
Redux Toolkit also includes a powerful data fetching and caching capability that we've dubbed "RTK Query". It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.
|
| 66 |
+
|
| 67 |
+
## What's Included
|
| 68 |
+
|
| 69 |
+
Redux Toolkit includes these APIs:
|
| 70 |
+
|
| 71 |
+
- `configureStore()`: wraps `createStore` to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, add whatever Redux middleware you supply, includes `redux-thunk` by default, and enables use of the Redux DevTools Extension.
|
| 72 |
+
- `createReducer()`: lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the [`immer` library](https://github.com/mweststrate/immer) to let you write simpler immutable updates with normal mutative code, like `state.todos[3].completed = true`.
|
| 73 |
+
- `createAction()`: generates an action creator function for the given action type string. The function itself has `toString()` defined, so that it can be used in place of the type constant.
|
| 74 |
+
- `createSlice()`: combines `createReducer()` + `createAction()`. Accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
|
| 75 |
+
- `combineSlices()`: combines multiple slices into a single reducer, and allows "lazy loading" of slices after initialisation.
|
| 76 |
+
- `createListenerMiddleware()`: 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. A lightweight alternative to Redux async middleware like sagas and observables.
|
| 77 |
+
- `createAsyncThunk()`: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches `pending/resolved/rejected` action types based on that promise
|
| 78 |
+
- `createEntityAdapter()`: generates a set of reusable reducers and selectors to manage normalized data in the store
|
| 79 |
+
- The `createSelector()` utility from the [Reselect](https://github.com/reduxjs/reselect) library, re-exported for ease of use.
|
| 80 |
+
|
| 81 |
+
For details, see [the Redux Toolkit API Reference section in the docs](https://redux-toolkit.js.org/api/configureStore).
|
| 82 |
+
|
| 83 |
+
## RTK Query
|
| 84 |
+
|
| 85 |
+
**RTK Query** is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
|
| 86 |
+
|
| 87 |
+
RTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.
|
| 88 |
+
|
| 89 |
+
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
|
| 90 |
+
|
| 91 |
+
```ts no-transpile
|
| 92 |
+
import { createApi } from '@reduxjs/toolkit/query'
|
| 93 |
+
|
| 94 |
+
/* React-specific entry point that automatically generates
|
| 95 |
+
hooks corresponding to the defined endpoints */
|
| 96 |
+
import { createApi } from '@reduxjs/toolkit/query/react'
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
### What's included
|
| 100 |
+
|
| 101 |
+
RTK Query includes these APIs:
|
| 102 |
+
|
| 103 |
+
- `createApi()`: The core of RTK Query's functionality. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. In most cases, you should use this once per app, with "one API slice per base URL" as a rule of thumb.
|
| 104 |
+
- `fetchBaseQuery()`: A small wrapper around fetch that aims to simplify requests. Intended as the recommended baseQuery to be used in createApi for the majority of users.
|
| 105 |
+
- `<ApiProvider />`: Can be used as a Provider if you do not already have a Redux store.
|
| 106 |
+
- `setupListeners()`: A utility used to enable refetchOnMount and refetchOnReconnect behaviors.
|
| 107 |
+
|
| 108 |
+
See the [**RTK Query Overview**](https://redux-toolkit.js.org/rtk-query/overview) page for more details on what RTK Query is, what problems it solves, and how to use it.
|
| 109 |
+
|
| 110 |
+
## Contributing
|
| 111 |
+
|
| 112 |
+
Please refer to our [contributing guide](/CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Redux Toolkit.
|
node_modules/@reduxjs/toolkit/package.json
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@reduxjs/toolkit",
|
| 3 |
+
"version": "2.12.0",
|
| 4 |
+
"description": "The official, opinionated, batteries-included toolset for efficient Redux development",
|
| 5 |
+
"author": "Mark Erikson <mark@isquaredsoftware.com>",
|
| 6 |
+
"license": "MIT",
|
| 7 |
+
"repository": {
|
| 8 |
+
"type": "git",
|
| 9 |
+
"url": "git+https://github.com/reduxjs/redux-toolkit.git"
|
| 10 |
+
},
|
| 11 |
+
"keywords": [
|
| 12 |
+
"redux",
|
| 13 |
+
"react",
|
| 14 |
+
"starter",
|
| 15 |
+
"toolkit",
|
| 16 |
+
"reducer",
|
| 17 |
+
"slice",
|
| 18 |
+
"immer",
|
| 19 |
+
"immutable",
|
| 20 |
+
"redux-toolkit",
|
| 21 |
+
"tanstack-intent"
|
| 22 |
+
],
|
| 23 |
+
"publishConfig": {
|
| 24 |
+
"access": "public"
|
| 25 |
+
},
|
| 26 |
+
"module": "dist/redux-toolkit.legacy-esm.js",
|
| 27 |
+
"main": "dist/cjs/index.js",
|
| 28 |
+
"types": "dist/index.d.ts",
|
| 29 |
+
"react-native": "dist/redux-toolkit.legacy-esm.js",
|
| 30 |
+
"unpkg": "dist/redux-toolkit.browser.mjs",
|
| 31 |
+
"exports": {
|
| 32 |
+
"./package.json": "./package.json",
|
| 33 |
+
".": {
|
| 34 |
+
"module-sync": {
|
| 35 |
+
"types": "./dist/index.d.mts",
|
| 36 |
+
"default": "./dist/redux-toolkit.modern.mjs"
|
| 37 |
+
},
|
| 38 |
+
"module": {
|
| 39 |
+
"types": "./dist/index.d.mts",
|
| 40 |
+
"default": "./dist/redux-toolkit.modern.mjs"
|
| 41 |
+
},
|
| 42 |
+
"react-native": {
|
| 43 |
+
"import": {
|
| 44 |
+
"types": "./dist/index.d.mts",
|
| 45 |
+
"default": "./dist/redux-toolkit.modern.mjs"
|
| 46 |
+
},
|
| 47 |
+
"default": {
|
| 48 |
+
"types": "./dist/index.d.ts",
|
| 49 |
+
"default": "./dist/cjs/index.js"
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"browser": {
|
| 53 |
+
"import": {
|
| 54 |
+
"types": "./dist/index.d.mts",
|
| 55 |
+
"default": "./dist/redux-toolkit.browser.mjs"
|
| 56 |
+
},
|
| 57 |
+
"default": {
|
| 58 |
+
"types": "./dist/index.d.ts",
|
| 59 |
+
"default": "./dist/cjs/index.js"
|
| 60 |
+
}
|
| 61 |
+
},
|
| 62 |
+
"import": {
|
| 63 |
+
"types": "./dist/index.d.mts",
|
| 64 |
+
"default": "./dist/redux-toolkit.modern.mjs"
|
| 65 |
+
},
|
| 66 |
+
"default": {
|
| 67 |
+
"types": "./dist/index.d.ts",
|
| 68 |
+
"default": "./dist/cjs/index.js"
|
| 69 |
+
}
|
| 70 |
+
},
|
| 71 |
+
"./react": {
|
| 72 |
+
"module-sync": {
|
| 73 |
+
"types": "./dist/react/index.d.mts",
|
| 74 |
+
"default": "./dist/react/redux-toolkit-react.modern.mjs"
|
| 75 |
+
},
|
| 76 |
+
"module": {
|
| 77 |
+
"types": "./dist/react/index.d.mts",
|
| 78 |
+
"default": "./dist/react/redux-toolkit-react.modern.mjs"
|
| 79 |
+
},
|
| 80 |
+
"react-native": {
|
| 81 |
+
"import": {
|
| 82 |
+
"types": "./dist/react/index.d.mts",
|
| 83 |
+
"default": "./dist/react/redux-toolkit-react.modern.mjs"
|
| 84 |
+
},
|
| 85 |
+
"default": {
|
| 86 |
+
"types": "./dist/react/index.d.ts",
|
| 87 |
+
"default": "./dist/react/cjs/index.js"
|
| 88 |
+
}
|
| 89 |
+
},
|
| 90 |
+
"browser": {
|
| 91 |
+
"import": {
|
| 92 |
+
"types": "./dist/react/index.d.mts",
|
| 93 |
+
"default": "./dist/react/redux-toolkit-react.browser.mjs"
|
| 94 |
+
},
|
| 95 |
+
"default": {
|
| 96 |
+
"types": "./dist/react/index.d.ts",
|
| 97 |
+
"default": "./dist/react/cjs/index.js"
|
| 98 |
+
}
|
| 99 |
+
},
|
| 100 |
+
"import": {
|
| 101 |
+
"types": "./dist/react/index.d.mts",
|
| 102 |
+
"default": "./dist/react/redux-toolkit-react.modern.mjs"
|
| 103 |
+
},
|
| 104 |
+
"default": {
|
| 105 |
+
"types": "./dist/react/index.d.ts",
|
| 106 |
+
"default": "./dist/react/cjs/index.js"
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
"./query": {
|
| 110 |
+
"module-sync": {
|
| 111 |
+
"types": "./dist/query/index.d.mts",
|
| 112 |
+
"default": "./dist/query/rtk-query.modern.mjs"
|
| 113 |
+
},
|
| 114 |
+
"module": {
|
| 115 |
+
"types": "./dist/query/index.d.mts",
|
| 116 |
+
"default": "./dist/query/rtk-query.modern.mjs"
|
| 117 |
+
},
|
| 118 |
+
"react-native": {
|
| 119 |
+
"import": {
|
| 120 |
+
"types": "./dist/query/index.d.mts",
|
| 121 |
+
"default": "./dist/query/rtk-query.modern.mjs"
|
| 122 |
+
},
|
| 123 |
+
"default": {
|
| 124 |
+
"types": "./dist/query/index.d.ts",
|
| 125 |
+
"default": "./dist/query/cjs/index.js"
|
| 126 |
+
}
|
| 127 |
+
},
|
| 128 |
+
"browser": {
|
| 129 |
+
"import": {
|
| 130 |
+
"types": "./dist/query/index.d.mts",
|
| 131 |
+
"default": "./dist/query/rtk-query.browser.mjs"
|
| 132 |
+
},
|
| 133 |
+
"default": {
|
| 134 |
+
"types": "./dist/query/index.d.ts",
|
| 135 |
+
"default": "./dist/query/cjs/index.js"
|
| 136 |
+
}
|
| 137 |
+
},
|
| 138 |
+
"import": {
|
| 139 |
+
"types": "./dist/query/index.d.mts",
|
| 140 |
+
"default": "./dist/query/rtk-query.modern.mjs"
|
| 141 |
+
},
|
| 142 |
+
"default": {
|
| 143 |
+
"types": "./dist/query/index.d.ts",
|
| 144 |
+
"default": "./dist/query/cjs/index.js"
|
| 145 |
+
}
|
| 146 |
+
},
|
| 147 |
+
"./query/react": {
|
| 148 |
+
"module-sync": {
|
| 149 |
+
"types": "./dist/query/react/index.d.mts",
|
| 150 |
+
"default": "./dist/query/react/rtk-query-react.modern.mjs"
|
| 151 |
+
},
|
| 152 |
+
"module": {
|
| 153 |
+
"types": "./dist/query/react/index.d.mts",
|
| 154 |
+
"default": "./dist/query/react/rtk-query-react.modern.mjs"
|
| 155 |
+
},
|
| 156 |
+
"react-native": {
|
| 157 |
+
"import": {
|
| 158 |
+
"types": "./dist/query/react/index.d.mts",
|
| 159 |
+
"default": "./dist/query/react/rtk-query-react.modern.mjs"
|
| 160 |
+
},
|
| 161 |
+
"default": {
|
| 162 |
+
"types": "./dist/query/react/index.d.ts",
|
| 163 |
+
"default": "./dist/query/react/cjs/index.js"
|
| 164 |
+
}
|
| 165 |
+
},
|
| 166 |
+
"browser": {
|
| 167 |
+
"import": {
|
| 168 |
+
"types": "./dist/query/react/index.d.mts",
|
| 169 |
+
"default": "./dist/query/react/rtk-query-react.browser.mjs"
|
| 170 |
+
},
|
| 171 |
+
"default": {
|
| 172 |
+
"types": "./dist/query/react/index.d.ts",
|
| 173 |
+
"default": "./dist/query/react/cjs/index.js"
|
| 174 |
+
}
|
| 175 |
+
},
|
| 176 |
+
"import": {
|
| 177 |
+
"types": "./dist/query/react/index.d.mts",
|
| 178 |
+
"default": "./dist/query/react/rtk-query-react.modern.mjs"
|
| 179 |
+
},
|
| 180 |
+
"default": {
|
| 181 |
+
"types": "./dist/query/react/index.d.ts",
|
| 182 |
+
"default": "./dist/query/react/cjs/index.js"
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
},
|
| 186 |
+
"devDependencies": {
|
| 187 |
+
"@arethetypeswrong/cli": "^0.18.2",
|
| 188 |
+
"@babel/core": "^7.24.8",
|
| 189 |
+
"@babel/helper-module-imports": "^7.24.7",
|
| 190 |
+
"@microsoft/api-extractor": "^7.13.2",
|
| 191 |
+
"@phryneas/ts-version": "^1.0.2",
|
| 192 |
+
"@size-limit/file": "^11.0.1",
|
| 193 |
+
"@size-limit/webpack": "^11.0.1",
|
| 194 |
+
"@tanstack/intent": "^0.0.19",
|
| 195 |
+
"@testing-library/dom": "^10.4.0",
|
| 196 |
+
"@testing-library/react": "^16.0.1",
|
| 197 |
+
"@testing-library/react-render-stream": "^1.0.3",
|
| 198 |
+
"@testing-library/user-event": "^14.5.2",
|
| 199 |
+
"@types/babel__core": "^7.20.5",
|
| 200 |
+
"@types/babel__helper-module-imports": "^7.18.3",
|
| 201 |
+
"@types/node": "^25.5.0",
|
| 202 |
+
"@types/query-string": "^6.3.0",
|
| 203 |
+
"@types/react": "^19.0.1",
|
| 204 |
+
"@types/react-dom": "^19.0.1",
|
| 205 |
+
"@typescript-eslint/eslint-plugin": "^6",
|
| 206 |
+
"@typescript-eslint/parser": "^6",
|
| 207 |
+
"axios": "^0.19.2",
|
| 208 |
+
"esbuild": "^0.25.1",
|
| 209 |
+
"esbuild-extra": "^0.4.0",
|
| 210 |
+
"eslint": "^7.25.0",
|
| 211 |
+
"eslint-config-prettier": "^9.1.0",
|
| 212 |
+
"eslint-config-react-app": "^7.0.1",
|
| 213 |
+
"eslint-plugin-flowtype": "^5.7.2",
|
| 214 |
+
"eslint-plugin-import": "^2.22.1",
|
| 215 |
+
"eslint-plugin-jsx-a11y": "^6.4.1",
|
| 216 |
+
"eslint-plugin-prettier": "^5.1.3",
|
| 217 |
+
"eslint-plugin-react": "^7.23.2",
|
| 218 |
+
"eslint-plugin-react-hooks": "^4.2.0",
|
| 219 |
+
"jsdom": "^25.0.1",
|
| 220 |
+
"msw": "^2.1.4",
|
| 221 |
+
"node-fetch": "^3.3.2",
|
| 222 |
+
"prettier": "^3.2.5",
|
| 223 |
+
"query-string": "^7.0.1",
|
| 224 |
+
"react": "^19.0.0",
|
| 225 |
+
"react-dom": "^19.0.0",
|
| 226 |
+
"react-redux": "^9.2.0",
|
| 227 |
+
"rimraf": "^6.1.3",
|
| 228 |
+
"size-limit": "^11.0.1",
|
| 229 |
+
"tsup": "^8.4.0",
|
| 230 |
+
"tsx": "^4.19.0",
|
| 231 |
+
"typescript": "^5.9.3",
|
| 232 |
+
"valibot": "^1.0.0",
|
| 233 |
+
"vite-tsconfig-paths": "^4.3.1",
|
| 234 |
+
"vitest": "^4"
|
| 235 |
+
},
|
| 236 |
+
"scripts": {
|
| 237 |
+
"clean": "rimraf dist",
|
| 238 |
+
"run-build": "tsup --config=$INIT_CWD/tsup.config.mts",
|
| 239 |
+
"build": "yarn clean && yarn run-build && tsx scripts/fixUniqueSymbolExports.mts",
|
| 240 |
+
"build-only": "yarn clean && yarn run-build",
|
| 241 |
+
"format": "prettier --write \"(src|examples)/**/*.{ts,tsx}\" \"**/*.md\"",
|
| 242 |
+
"format:check": "prettier --list-different \"(src|examples)/**/*.{ts,tsx}\" \"docs/*/**.md\"",
|
| 243 |
+
"lint": "eslint src examples",
|
| 244 |
+
"test": "vitest --typecheck --run ",
|
| 245 |
+
"test:watch": "vitest --watch",
|
| 246 |
+
"type-tests": "yarn tsc -p tsconfig.test.json --noEmit",
|
| 247 |
+
"prepack": "yarn build",
|
| 248 |
+
"size": "size-limit"
|
| 249 |
+
},
|
| 250 |
+
"files": [
|
| 251 |
+
"dist/",
|
| 252 |
+
"src/",
|
| 253 |
+
"!src/**/tests/**",
|
| 254 |
+
"!src/**/*.{test,spec}(-d)?.(c|m)[tj]sx?",
|
| 255 |
+
"query",
|
| 256 |
+
"react",
|
| 257 |
+
"skills",
|
| 258 |
+
"!skills/_artifacts"
|
| 259 |
+
],
|
| 260 |
+
"dependencies": {
|
| 261 |
+
"@standard-schema/spec": "^1.0.0",
|
| 262 |
+
"@standard-schema/utils": "^0.3.0",
|
| 263 |
+
"immer": "^11.0.0",
|
| 264 |
+
"redux": "^5.0.1",
|
| 265 |
+
"redux-thunk": "^3.1.0",
|
| 266 |
+
"reselect": "^5.1.0"
|
| 267 |
+
},
|
| 268 |
+
"peerDependencies": {
|
| 269 |
+
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
|
| 270 |
+
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
|
| 271 |
+
},
|
| 272 |
+
"peerDependenciesMeta": {
|
| 273 |
+
"react": {
|
| 274 |
+
"optional": true
|
| 275 |
+
},
|
| 276 |
+
"react-redux": {
|
| 277 |
+
"optional": true
|
| 278 |
+
}
|
| 279 |
+
},
|
| 280 |
+
"sideEffects": false,
|
| 281 |
+
"bugs": {
|
| 282 |
+
"url": "https://github.com/reduxjs/redux-toolkit/issues"
|
| 283 |
+
},
|
| 284 |
+
"homepage": "https://redux-toolkit.js.org"
|
| 285 |
+
}
|
node_modules/@reduxjs/toolkit/query/package.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@reduxjs/toolkit-query",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"description": "",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"module": "../dist/query/rtk-query.legacy-esm.js",
|
| 7 |
+
"main": "../dist/query/cjs/index.js",
|
| 8 |
+
"types": "./../dist/query/index.d.ts",
|
| 9 |
+
"react-native": "./../dist/query/rtk-query.legacy-esm.js",
|
| 10 |
+
"author": "Mark Erikson <mark@isquaredsoftware.com>",
|
| 11 |
+
"license": "MIT",
|
| 12 |
+
"sideEffects": false
|
| 13 |
+
}
|
node_modules/@reduxjs/toolkit/query/react/package.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@reduxjs/toolkit-query-react",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"description": "",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"module": "../../dist/query/react/rtk-query-react.legacy-esm.js",
|
| 7 |
+
"main": "../../dist/query/react/cjs/index.js",
|
| 8 |
+
"types": "./../../dist/query/react/index.d.ts",
|
| 9 |
+
"react-native": "./../../dist/query/react/rtk-query-react.legacy-esm.js",
|
| 10 |
+
"author": "Mark Erikson <mark@isquaredsoftware.com>",
|
| 11 |
+
"license": "MIT",
|
| 12 |
+
"sideEffects": false
|
| 13 |
+
}
|
node_modules/@reduxjs/toolkit/react/package.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@reduxjs/toolkit-react",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"description": "",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"module": "../dist/react/redux-toolkit-react.legacy-esm.js",
|
| 7 |
+
"main": "./../dist/react/redux-toolkit-react.modern.mjs",
|
| 8 |
+
"types": "./../dist/react/index.d.ts",
|
| 9 |
+
"react-native": "./../dist/react/redux-toolkit-react.modern.mjs",
|
| 10 |
+
"author": "Mark Erikson <mark@isquared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ing
|
| 5 |
+
React + Redux codebase. Covers configureStore, Provider wiring, typed hooks,
|
| 6 |
+
hooks-first React-Redux usage, feature folders, and the correct store lifetime
|
| 7 |
+
for SPA and SSR-heavy React environments.
|
| 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-toolkit:docs/tutorials/quick-start.mdx"
|
| 15 |
+
- "reduxjs/redux-toolkit:docs/tutorials/typescript.md"
|
| 16 |
+
- "reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx"
|
| 17 |
+
- "reduxjs/redux-toolkit:docs/usage/nextjs.mdx"
|
| 18 |
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
# Modern Redux
|
| 22 |
+
|
| 23 |
+
## Setup
|
| 24 |
+
|
| 25 |
+
```tsx
|
| 26 |
+
// file: src/features/counter/counterSlice.ts
|
| 27 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 28 |
+
|
| 29 |
+
export const counterSlice = createSlice({
|
| 30 |
+
name: 'counter',
|
| 31 |
+
initialState: { value: 0 },
|
| 32 |
+
reducers: {
|
| 33 |
+
increment(state) {
|
| 34 |
+
state.value += 1
|
| 35 |
+
},
|
| 36 |
+
},
|
| 37 |
+
})
|
| 38 |
+
|
| 39 |
+
export const { increment } = counterSlice.actions
|
| 40 |
+
|
| 41 |
+
// file: src/app/store.ts
|
| 42 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 43 |
+
import { counterSlice } from '../features/counter/counterSlice'
|
| 44 |
+
|
| 45 |
+
export const store = configureStore({
|
| 46 |
+
reducer: {
|
| 47 |
+
counter: counterSlice.reducer,
|
| 48 |
+
},
|
| 49 |
+
})
|
| 50 |
+
|
| 51 |
+
export type RootState = ReturnType<typeof store.getState>
|
| 52 |
+
export type AppDispatch = typeof store.dispatch
|
| 53 |
+
|
| 54 |
+
// file: src/app/hooks.ts
|
| 55 |
+
import { useDispatch, useSelector } from 'react-redux'
|
| 56 |
+
import type { AppDispatch, RootState } from './store'
|
| 57 |
+
|
| 58 |
+
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
|
| 59 |
+
export const useAppSelector = useSelector.withTypes<RootState>()
|
| 60 |
+
|
| 61 |
+
// file: src/features/counter/Counter.tsx
|
| 62 |
+
import { increment } from './counterSlice'
|
| 63 |
+
import { useAppDispatch, useAppSelector } from '../../app/hooks'
|
| 64 |
+
|
| 65 |
+
export function Counter() {
|
| 66 |
+
const value = useAppSelector((state) => state.counter.value)
|
| 67 |
+
const dispatch = useAppDispatch()
|
| 68 |
+
|
| 69 |
+
return <button onClick={() => dispatch(increment())}>{value}</button>
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
// file: src/main.tsx
|
| 73 |
+
import React from 'react'
|
| 74 |
+
import ReactDOM from 'react-dom/client'
|
| 75 |
+
import { Provider } from 'react-redux'
|
| 76 |
+
import { store } from './app/store'
|
| 77 |
+
import { Counter } from './features/counter/Counter'
|
| 78 |
+
|
| 79 |
+
ReactDOM.createRoot(document.getElementById('root')!).render(
|
| 80 |
+
<Provider store={store}>
|
| 81 |
+
<Counter />
|
| 82 |
+
</Provider>,
|
| 83 |
+
)
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
## Core Patterns
|
| 87 |
+
|
| 88 |
+
### Keep React components on hooks, not wrappers
|
| 89 |
+
|
| 90 |
+
```tsx
|
| 91 |
+
import { postAdded, selectPosts } from './postsSlice'
|
| 92 |
+
import { useAppDispatch, useAppSelector } from '../../app/hooks'
|
| 93 |
+
|
| 94 |
+
export function PostsList() {
|
| 95 |
+
const posts = useAppSelector(selectPosts)
|
| 96 |
+
const dispatch = useAppDispatch()
|
| 97 |
+
|
| 98 |
+
return (
|
| 99 |
+
<button
|
| 100 |
+
onClick={() =>
|
| 101 |
+
dispatch(postAdded({ id: 'p2', title: 'Write docs' }))
|
| 102 |
+
}
|
| 103 |
+
>
|
| 104 |
+
{posts.length}
|
| 105 |
+
</button>
|
| 106 |
+
)
|
| 107 |
+
}
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
Hooks are the default React-Redux integration for new code.
|
| 111 |
+
|
| 112 |
+
### Create the store inside the provider for SSR-heavy React apps
|
| 113 |
+
|
| 114 |
+
```tsx
|
| 115 |
+
// file: src/lib/store.ts
|
| 116 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 117 |
+
import { counterSlice } from '../features/counter/counterSlice'
|
| 118 |
+
|
| 119 |
+
export const makeStore = () =>
|
| 120 |
+
configureStore({
|
| 121 |
+
reducer: {
|
| 122 |
+
counter: counterSlice.reducer,
|
| 123 |
+
},
|
| 124 |
+
})
|
| 125 |
+
|
| 126 |
+
export type AppStore = ReturnType<typeof makeStore>
|
| 127 |
+
export type RootState = ReturnType<AppStore['getState']>
|
| 128 |
+
export type AppDispatch = AppStore['dispatch']
|
| 129 |
+
|
| 130 |
+
// file: src/app/StoreProvider.tsx
|
| 131 |
+
'use client'
|
| 132 |
+
|
| 133 |
+
import { useState, type ReactNode } from 'react'
|
| 134 |
+
import { Provider } from 'react-redux'
|
| 135 |
+
import { makeStore } from '../lib/store'
|
| 136 |
+
|
| 137 |
+
export function StoreProvider({ children }: { children: ReactNode }) {
|
| 138 |
+
const [store] = useState(makeStore)
|
| 139 |
+
|
| 140 |
+
return <Provider store={store}>{children}</Provider>
|
| 141 |
+
}
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
In SSR-heavy React frameworks, create a store per request and keep that instance stable across renders.
|
| 145 |
+
|
| 146 |
+
### Keep app wiring in `app/` and feature logic in feature folders
|
| 147 |
+
|
| 148 |
+
```text
|
| 149 |
+
src/
|
| 150 |
+
app/
|
| 151 |
+
store.ts
|
| 152 |
+
hooks.ts
|
| 153 |
+
features/
|
| 154 |
+
posts/
|
| 155 |
+
postsSlice.ts
|
| 156 |
+
PostsList.tsx
|
| 157 |
+
users/
|
| 158 |
+
usersSlice.ts
|
| 159 |
+
UsersList.tsx
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
This keeps store wiring centralized and feature logic colocated.
|
| 163 |
+
|
| 164 |
+
## Common Mistakes
|
| 165 |
+
|
| 166 |
+
### HIGH Importing the store in React components
|
| 167 |
+
|
| 168 |
+
Wrong:
|
| 169 |
+
|
| 170 |
+
```tsx
|
| 171 |
+
import { store } from '../../app/store'
|
| 172 |
+
|
| 173 |
+
export function PostsList() {
|
| 174 |
+
const posts = store.getState().posts
|
| 175 |
+
return <div>{posts.length}</div>
|
| 176 |
+
}
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
Correct:
|
| 180 |
+
|
| 181 |
+
```tsx
|
| 182 |
+
import { useAppSelector } from '../../app/hooks'
|
| 183 |
+
|
| 184 |
+
export function PostsList() {
|
| 185 |
+
const posts = useAppSelector((state) => state.posts)
|
| 186 |
+
return <div>{posts.length}</div>
|
| 187 |
+
}
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
React components should read through context and hooks; direct store imports are a separate escape hatch for non-React integrations, not the default UI pattern.
|
| 191 |
+
|
| 192 |
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
| 193 |
+
|
| 194 |
+
### HIGH Defaulting to `connect()` in new React code
|
| 195 |
+
|
| 196 |
+
Wrong:
|
| 197 |
+
|
| 198 |
+
```tsx
|
| 199 |
+
import { connect } from 'react-redux'
|
| 200 |
+
|
| 201 |
+
const increment = () => ({ type: 'counter/increment' as const })
|
| 202 |
+
const mapState = (state: { counter: { value: number } }) => ({
|
| 203 |
+
value: state.counter.value,
|
| 204 |
+
})
|
| 205 |
+
const mapDispatch = { increment }
|
| 206 |
+
|
| 207 |
+
function Counter({ value, increment }: ReturnType<typeof mapState> & typeof mapDispatch) {
|
| 208 |
+
return <button onClick={() => increment()}>{value}</button>
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
export default connect(mapState, mapDispatch)(Counter)
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
Correct:
|
| 215 |
+
|
| 216 |
+
```tsx
|
| 217 |
+
import { increment } from './counterSlice'
|
| 218 |
+
import { useAppDispatch, useAppSelector } from '../../app/hooks'
|
| 219 |
+
|
| 220 |
+
export function Counter() {
|
| 221 |
+
const value = useAppSelector((state) => state.counter.value)
|
| 222 |
+
const dispatch = useAppDispatch()
|
| 223 |
+
|
| 224 |
+
return <button onClick={() => dispatch(increment())}>{value}</button>
|
| 225 |
+
}
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
Hooks are the modern default, simpler to type, and the maintainers explicitly want agents to steer new code away from `connect`.
|
| 229 |
+
|
| 230 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx
|
| 231 |
+
|
| 232 |
+
### HIGH Recreating the store during render in SSR-heavy apps
|
| 233 |
+
|
| 234 |
+
Wrong:
|
| 235 |
+
|
| 236 |
+
```tsx
|
| 237 |
+
'use client'
|
| 238 |
+
|
| 239 |
+
import { Provider } from 'react-redux'
|
| 240 |
+
import { makeStore } from '../lib/store'
|
| 241 |
+
|
| 242 |
+
export function StoreProvider({ children }: { children: import('react').ReactNode }) {
|
| 243 |
+
const store = makeStore()
|
| 244 |
+
return <Provider store={store}>{children}</Provider>
|
| 245 |
+
}
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
Correct:
|
| 249 |
+
|
| 250 |
+
```tsx
|
| 251 |
+
'use client'
|
| 252 |
+
|
| 253 |
+
import { useState } from 'react'
|
| 254 |
+
import { Provider } from 'react-redux'
|
| 255 |
+
import { makeStore } from '../lib/store'
|
| 256 |
+
|
| 257 |
+
export function StoreProvider({ children }: { children: import('react').ReactNode }) {
|
| 258 |
+
const [store] = useState(makeStore)
|
| 259 |
+
return <Provider store={store}>{children}</Provider>
|
| 260 |
+
}
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
A new store on every render loses client state, while a module singleton can leak across requests on the server.
|
| 264 |
+
|
| 265 |
+
Source: reduxjs/redux-toolkit:docs/usage/nextjs.mdx
|
| 266 |
+
|
| 267 |
+
### HIGH Keeping `createStore` boilerplate as the default
|
| 268 |
+
|
| 269 |
+
Wrong:
|
| 270 |
+
|
| 271 |
+
```ts
|
| 272 |
+
import { applyMiddleware, combineReducers, createStore } from 'redux'
|
| 273 |
+
import thunk from 'redux-thunk'
|
| 274 |
+
|
| 275 |
+
const counterReducer = (state = { value: 0 }) => state
|
| 276 |
+
|
| 277 |
+
const rootReducer = combineReducers({
|
| 278 |
+
counter: counterReducer,
|
| 279 |
+
})
|
| 280 |
+
|
| 281 |
+
export const store = createStore(rootReducer, applyMiddleware(thunk))
|
| 282 |
+
```
|
| 283 |
+
|
| 284 |
+
Correct:
|
| 285 |
+
|
| 286 |
+
```ts
|
| 287 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 288 |
+
|
| 289 |
+
const counterReducer = (state = { value: 0 }) => state
|
| 290 |
+
|
| 291 |
+
export const store = configureStore({
|
| 292 |
+
reducer: {
|
| 293 |
+
counter: counterReducer,
|
| 294 |
+
},
|
| 295 |
+
})
|
| 296 |
+
```
|
| 297 |
+
|
| 298 |
+
Manual store setup works, but it throws away RTK's default middleware, dev checks, and the current recommended baseline.
|
| 299 |
+
|
| 300 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx
|
| 301 |
+
|
| 302 |
+
## References
|
| 303 |
+
|
| 304 |
+
- [Store lifetime and framework boundaries](references/store-lifetime.md)
|
node_modules/@reduxjs/toolkit/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md
ADDED
|
@@ -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.
|
node_modules/@reduxjs/toolkit/skills/build-modern-redux-apps/redux-dataflow/SKILL.md
ADDED
|
@@ -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
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
node_modules/@reduxjs/toolkit/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: evolve-and-diagnose-redux-apps/migrate-to-modern-redux
|
| 3 |
+
description: >
|
| 4 |
+
Use this when moving a legacy Redux codebase to current RTK patterns. Covers
|
| 5 |
+
replacing createStore with configureStore, migrating touched reducers to
|
| 6 |
+
createSlice, codemod-assisted RTK 2 updates, and replacing server-data stacks
|
| 7 |
+
with RTK Query instead of writing new legacy Redux code.
|
| 8 |
+
type: lifecycle
|
| 9 |
+
library: "@reduxjs/toolkit"
|
| 10 |
+
library_version: "2.11.2"
|
| 11 |
+
requires:
|
| 12 |
+
- build-modern-redux-apps/modern-redux
|
| 13 |
+
sources:
|
| 14 |
+
- "reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx"
|
| 15 |
+
- "reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md"
|
| 16 |
+
- "reduxjs/redux-toolkit:packages/rtk-codemods/README.md"
|
| 17 |
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# Migrate To Modern Redux
|
| 21 |
+
|
| 22 |
+
## Setup
|
| 23 |
+
|
| 24 |
+
```ts
|
| 25 |
+
// before
|
| 26 |
+
import { applyMiddleware, combineReducers, createStore } from 'redux'
|
| 27 |
+
import thunk from 'redux-thunk'
|
| 28 |
+
|
| 29 |
+
const postsReducer = (state = [] as { id: string; title: string }[]) => state
|
| 30 |
+
const usersReducer = (state = [] as { id: string; name: string }[]) => state
|
| 31 |
+
|
| 32 |
+
const rootReducer = combineReducers({
|
| 33 |
+
posts: postsReducer,
|
| 34 |
+
users: usersReducer,
|
| 35 |
+
})
|
| 36 |
+
|
| 37 |
+
export const legacyStore = createStore(rootReducer, applyMiddleware(thunk))
|
| 38 |
+
|
| 39 |
+
// after
|
| 40 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 41 |
+
|
| 42 |
+
const postsReducer = (state = [] as { id: string; title: string }[]) => state
|
| 43 |
+
const usersReducer = (state = [] as { id: string; name: string }[]) => state
|
| 44 |
+
|
| 45 |
+
export const store = configureStore({
|
| 46 |
+
reducer: {
|
| 47 |
+
posts: postsReducer,
|
| 48 |
+
users: usersReducer,
|
| 49 |
+
},
|
| 50 |
+
})
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## Core Patterns
|
| 54 |
+
|
| 55 |
+
### Replace the store setup first
|
| 56 |
+
|
| 57 |
+
```ts
|
| 58 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 59 |
+
|
| 60 |
+
const postsReducer = (state = [] as { id: string; title: string }[]) => state
|
| 61 |
+
const usersReducer = (state = [] as { id: string; name: string }[]) => state
|
| 62 |
+
|
| 63 |
+
export const store = configureStore({
|
| 64 |
+
reducer: {
|
| 65 |
+
posts: postsReducer,
|
| 66 |
+
users: usersReducer,
|
| 67 |
+
},
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
export type RootState = ReturnType<typeof store.getState>
|
| 71 |
+
export type AppDispatch = typeof store.dispatch
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
This is the one migration step that can happen immediately while old reducers continue to work.
|
| 75 |
+
|
| 76 |
+
### Migrate reducers as you touch them
|
| 77 |
+
|
| 78 |
+
```ts
|
| 79 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 80 |
+
|
| 81 |
+
type TodosState = {
|
| 82 |
+
items: { id: string; text: string; completed: boolean }[]
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
const initialState: TodosState = {
|
| 86 |
+
items: [],
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
export const todosSlice = createSlice({
|
| 90 |
+
name: 'todos',
|
| 91 |
+
initialState,
|
| 92 |
+
reducers: {
|
| 93 |
+
todoAdded(state, action: { payload: { id: string; text: string } }) {
|
| 94 |
+
state.items.push({ ...action.payload, completed: false })
|
| 95 |
+
},
|
| 96 |
+
todoToggled(state, action: { payload: { id: string } }) {
|
| 97 |
+
const todo = state.items.find((item) => item.id === action.payload.id)
|
| 98 |
+
if (todo) {
|
| 99 |
+
todo.completed = !todo.completed
|
| 100 |
+
}
|
| 101 |
+
},
|
| 102 |
+
},
|
| 103 |
+
})
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Once a reducer needs editing, migrate that reducer instead of adding more legacy code to it.
|
| 107 |
+
|
| 108 |
+
### Use codemods for mechanical updates
|
| 109 |
+
|
| 110 |
+
```bash
|
| 111 |
+
npx @reduxjs/rtk-codemods createSliceBuilder src/features/posts/postsSlice.ts
|
| 112 |
+
npx @reduxjs/rtk-codemods createReducerBuilder src/features/posts/postsReducer.ts
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
Use codemods for repetitive RTK API migrations, then review the result and finish the semantic cleanup by hand.
|
| 116 |
+
|
| 117 |
+
### Replace legacy server-data stacks with RTK Query
|
| 118 |
+
|
| 119 |
+
```ts
|
| 120 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 121 |
+
|
| 122 |
+
type Todo = { id: string; text: string }
|
| 123 |
+
|
| 124 |
+
export const api = createApi({
|
| 125 |
+
reducerPath: 'api',
|
| 126 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 127 |
+
endpoints: (build) => ({
|
| 128 |
+
getTodos: build.query<Todo[], void>({
|
| 129 |
+
query: () => 'todos',
|
| 130 |
+
}),
|
| 131 |
+
}),
|
| 132 |
+
})
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
When the old code is just request status plus fetched data, migrate toward RTK Query instead of carrying the thunk stack forward forever.
|
| 136 |
+
|
| 137 |
+
## Common Mistakes
|
| 138 |
+
|
| 139 |
+
### HIGH Attempting a big-bang rewrite
|
| 140 |
+
|
| 141 |
+
Wrong:
|
| 142 |
+
|
| 143 |
+
```ts
|
| 144 |
+
// Replace every reducer, every connected component, and every async flow
|
| 145 |
+
// in one branch before shipping anything.
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
Correct:
|
| 149 |
+
|
| 150 |
+
```ts
|
| 151 |
+
// 1) Switch createStore to configureStore
|
| 152 |
+
// 2) Migrate one touched reducer to createSlice
|
| 153 |
+
// 3) Convert touched connected components to hooks
|
| 154 |
+
// 4) Repeat without introducing new legacy Redux code
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
Modern Redux migration is incremental, but once the store is modernized new work should stop adding legacy patterns.
|
| 158 |
+
|
| 159 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx
|
| 160 |
+
|
| 161 |
+
### CRITICAL Carrying removed RTK 2 config forms forward
|
| 162 |
+
|
| 163 |
+
Wrong:
|
| 164 |
+
|
| 165 |
+
```ts
|
| 166 |
+
configureStore({
|
| 167 |
+
reducer,
|
| 168 |
+
middleware: [logger],
|
| 169 |
+
})
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
Correct:
|
| 173 |
+
|
| 174 |
+
```ts
|
| 175 |
+
configureStore({
|
| 176 |
+
reducer,
|
| 177 |
+
middleware: (getDefaultMiddleware) =>
|
| 178 |
+
getDefaultMiddleware().concat(logger),
|
| 179 |
+
})
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
RTK 2 removed array middleware configuration and other older builder forms that agents trained on RTK 1.x still emit.
|
| 183 |
+
|
| 184 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md
|
| 185 |
+
|
| 186 |
+
### HIGH Preserving hand-written fetch state by default
|
| 187 |
+
|
| 188 |
+
Wrong:
|
| 189 |
+
|
| 190 |
+
```ts
|
| 191 |
+
import { createAsyncThunk } from '@reduxjs/toolkit'
|
| 192 |
+
|
| 193 |
+
type Todo = { id: string; text: string }
|
| 194 |
+
|
| 195 |
+
const initialState = {
|
| 196 |
+
items: [] as Todo[],
|
| 197 |
+
status: 'idle' as 'idle' | 'pending' | 'failed',
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
export const fetchTodos = createAsyncThunk('todos/fetch', async () => {
|
| 201 |
+
const response = await fetch('/api/todos')
|
| 202 |
+
return (await response.json()) as Todo[]
|
| 203 |
+
})
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Correct:
|
| 207 |
+
|
| 208 |
+
```ts
|
| 209 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 210 |
+
|
| 211 |
+
type Todo = { id: string; text: string }
|
| 212 |
+
|
| 213 |
+
const api = createApi({
|
| 214 |
+
reducerPath: 'api',
|
| 215 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 216 |
+
endpoints: (build) => ({
|
| 217 |
+
getTodos: build.query<Todo[], void>({
|
| 218 |
+
query: () => 'todos',
|
| 219 |
+
}),
|
| 220 |
+
}),
|
| 221 |
+
})
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
If the feature is really server cache, keep the migration moving toward RTK Query instead of rebuilding the old loading-flag architecture in new APIs.
|
| 225 |
+
|
| 226 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx
|
node_modules/@reduxjs/toolkit/skills/manage-server-data/adopt-rtk-query/SKILL.md
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: manage-server-data/adopt-rtk-query
|
| 3 |
+
description: >
|
| 4 |
+
Use this when adding RTK Query as the default server-data and document-cache
|
| 5 |
+
layer. Covers createApi, store integration, hooks, invalidation behavior,
|
| 6 |
+
optimistic updates, and deciding when RTK Query is the right cache model.
|
| 7 |
+
type: lifecycle
|
| 8 |
+
library: "@reduxjs/toolkit"
|
| 9 |
+
library_version: "2.11.2"
|
| 10 |
+
requires:
|
| 11 |
+
- build-modern-redux-apps/modern-redux
|
| 12 |
+
sources:
|
| 13 |
+
- "reduxjs/redux-toolkit:docs/rtk-query/api/createApi.mdx"
|
| 14 |
+
- "reduxjs/redux-toolkit:docs/rtk-query/usage/automated-refetching.mdx"
|
| 15 |
+
- "reduxjs/redux-toolkit:docs/rtk-query/usage/manual-cache-updates.mdx"
|
| 16 |
+
- "reduxjs/redux-toolkit:docs/rtk-query/usage/persistence-and-rehydration.mdx"
|
| 17 |
+
- "reduxjs/redux-toolkit:docs/tutorials/rtk-query.mdx"
|
| 18 |
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
# Adopt RTK Query
|
| 22 |
+
|
| 23 |
+
## Setup
|
| 24 |
+
|
| 25 |
+
```tsx
|
| 26 |
+
// file: src/services/api.ts
|
| 27 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 28 |
+
|
| 29 |
+
type Post = { id: string; title: string }
|
| 30 |
+
|
| 31 |
+
export const api = createApi({
|
| 32 |
+
reducerPath: 'api',
|
| 33 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 34 |
+
tagTypes: ['Post'],
|
| 35 |
+
endpoints: (build) => ({
|
| 36 |
+
getPosts: build.query<Post[], void>({
|
| 37 |
+
query: () => 'posts',
|
| 38 |
+
providesTags: (result) =>
|
| 39 |
+
result
|
| 40 |
+
? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']
|
| 41 |
+
: ['Post'],
|
| 42 |
+
}),
|
| 43 |
+
addPost: build.mutation<Post, Pick<Post, 'title'>>({
|
| 44 |
+
query: (body) => ({
|
| 45 |
+
url: 'posts',
|
| 46 |
+
method: 'POST',
|
| 47 |
+
body,
|
| 48 |
+
}),
|
| 49 |
+
invalidatesTags: ['Post'],
|
| 50 |
+
}),
|
| 51 |
+
}),
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
export const { useGetPostsQuery, useAddPostMutation } = api
|
| 55 |
+
|
| 56 |
+
// file: src/app/store.ts
|
| 57 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 58 |
+
import { api } from '../services/api'
|
| 59 |
+
|
| 60 |
+
export const store = configureStore({
|
| 61 |
+
reducer: {
|
| 62 |
+
[api.reducerPath]: api.reducer,
|
| 63 |
+
},
|
| 64 |
+
middleware: (getDefaultMiddleware) =>
|
| 65 |
+
getDefaultMiddleware().concat(api.middleware),
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
// file: src/App.tsx
|
| 69 |
+
import { Provider } from 'react-redux'
|
| 70 |
+
import { store } from './app/store'
|
| 71 |
+
import { useAddPostMutation, useGetPostsQuery } from './services/api'
|
| 72 |
+
|
| 73 |
+
function Posts() {
|
| 74 |
+
const { data: posts = [] } = useGetPostsQuery()
|
| 75 |
+
const [addPost] = useAddPostMutation()
|
| 76 |
+
|
| 77 |
+
return (
|
| 78 |
+
<div>
|
| 79 |
+
<button onClick={() => addPost({ title: 'Write docs' })}>Add</button>
|
| 80 |
+
<ul>
|
| 81 |
+
{posts.map((post) => (
|
| 82 |
+
<li key={post.id}>{post.title}</li>
|
| 83 |
+
))}
|
| 84 |
+
</ul>
|
| 85 |
+
</div>
|
| 86 |
+
)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
export function App() {
|
| 90 |
+
return (
|
| 91 |
+
<Provider store={store}>
|
| 92 |
+
<Posts />
|
| 93 |
+
</Provider>
|
| 94 |
+
)
|
| 95 |
+
}
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
## Core Patterns
|
| 99 |
+
|
| 100 |
+
### Keep one API slice per base URL and extend it
|
| 101 |
+
|
| 102 |
+
```ts
|
| 103 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 104 |
+
|
| 105 |
+
export const api = createApi({
|
| 106 |
+
reducerPath: 'api',
|
| 107 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 108 |
+
endpoints: () => ({}),
|
| 109 |
+
})
|
| 110 |
+
|
| 111 |
+
export const postsApi = api.injectEndpoints({
|
| 112 |
+
endpoints: (build) => ({
|
| 113 |
+
getPosts: build.query<{ id: string; title: string }[], void>({
|
| 114 |
+
query: () => 'posts',
|
| 115 |
+
}),
|
| 116 |
+
}),
|
| 117 |
+
})
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
Split files with `injectEndpoints`, not by making multiple `createApi` roots for the same backend.
|
| 121 |
+
|
| 122 |
+
### Use tags for cache invalidation
|
| 123 |
+
|
| 124 |
+
```ts
|
| 125 |
+
type Post = { id: string; title: string }
|
| 126 |
+
|
| 127 |
+
export const api = createApi({
|
| 128 |
+
reducerPath: 'api',
|
| 129 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 130 |
+
tagTypes: ['Post'],
|
| 131 |
+
endpoints: (build) => ({
|
| 132 |
+
getPosts: build.query<Post[], void>({
|
| 133 |
+
query: () => 'posts',
|
| 134 |
+
providesTags: (result) =>
|
| 135 |
+
result
|
| 136 |
+
? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']
|
| 137 |
+
: ['Post'],
|
| 138 |
+
}),
|
| 139 |
+
updatePost: build.mutation<Post, Pick<Post, 'id' | 'title'>>({
|
| 140 |
+
query: ({ id, title }) => ({
|
| 141 |
+
url: `posts/${id}`,
|
| 142 |
+
method: 'PATCH',
|
| 143 |
+
body: { title },
|
| 144 |
+
}),
|
| 145 |
+
invalidatesTags: (_result, _error, { id }) => [{ type: 'Post', id }],
|
| 146 |
+
}),
|
| 147 |
+
}),
|
| 148 |
+
})
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Treat tags as the normal invalidation path before reaching for manual cache patching.
|
| 152 |
+
|
| 153 |
+
### Do optimistic updates in endpoint lifecycles
|
| 154 |
+
|
| 155 |
+
```ts
|
| 156 |
+
type Post = { id: string; title: string }
|
| 157 |
+
|
| 158 |
+
export const api = createApi({
|
| 159 |
+
reducerPath: 'api',
|
| 160 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 161 |
+
tagTypes: ['Post'],
|
| 162 |
+
endpoints: (build) => ({
|
| 163 |
+
getPosts: build.query<Post[], void>({
|
| 164 |
+
query: () => 'posts',
|
| 165 |
+
providesTags: ['Post'],
|
| 166 |
+
}),
|
| 167 |
+
updatePostTitle: build.mutation<Post, Pick<Post, 'id' | 'title'>>({
|
| 168 |
+
query: ({ id, title }) => ({
|
| 169 |
+
url: `posts/${id}`,
|
| 170 |
+
method: 'PATCH',
|
| 171 |
+
body: { title },
|
| 172 |
+
}),
|
| 173 |
+
async onQueryStarted({ id, title }, { dispatch, queryFulfilled }) {
|
| 174 |
+
const patch = dispatch(
|
| 175 |
+
api.util.updateQueryData('getPosts', undefined, (draft) => {
|
| 176 |
+
const post = draft.find((item) => item.id === id)
|
| 177 |
+
if (post) {
|
| 178 |
+
post.title = title
|
| 179 |
+
}
|
| 180 |
+
}),
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
try {
|
| 184 |
+
await queryFulfilled
|
| 185 |
+
} catch {
|
| 186 |
+
patch.undo()
|
| 187 |
+
}
|
| 188 |
+
},
|
| 189 |
+
}),
|
| 190 |
+
}),
|
| 191 |
+
})
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Keep optimistic and pessimistic cache updates inside endpoint lifecycle handlers so they stay coupled to the request.
|
| 195 |
+
|
| 196 |
+
## Common Mistakes
|
| 197 |
+
|
| 198 |
+
### CRITICAL Creating multiple API slices for one backend
|
| 199 |
+
|
| 200 |
+
Wrong:
|
| 201 |
+
|
| 202 |
+
```ts
|
| 203 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 204 |
+
|
| 205 |
+
type User = { id: string; name: string }
|
| 206 |
+
|
| 207 |
+
const baseQuery = fetchBaseQuery({ baseUrl: '/api/' })
|
| 208 |
+
|
| 209 |
+
const postsApi = createApi({
|
| 210 |
+
reducerPath: 'api',
|
| 211 |
+
baseQuery,
|
| 212 |
+
endpoints: () => ({}),
|
| 213 |
+
})
|
| 214 |
+
|
| 215 |
+
const usersApi = createApi({
|
| 216 |
+
reducerPath: 'api',
|
| 217 |
+
baseQuery,
|
| 218 |
+
endpoints: () => ({}),
|
| 219 |
+
})
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
Correct:
|
| 223 |
+
|
| 224 |
+
```ts
|
| 225 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 226 |
+
|
| 227 |
+
type User = { id: string; name: string }
|
| 228 |
+
|
| 229 |
+
const baseQuery = fetchBaseQuery({ baseUrl: '/api/' })
|
| 230 |
+
|
| 231 |
+
const api = createApi({
|
| 232 |
+
reducerPath: 'api',
|
| 233 |
+
baseQuery,
|
| 234 |
+
endpoints: () => ({}),
|
| 235 |
+
})
|
| 236 |
+
|
| 237 |
+
const usersApi = api.injectEndpoints({
|
| 238 |
+
endpoints: (build) => ({
|
| 239 |
+
getUsers: build.query<User[], void>({ query: () => 'users' }),
|
| 240 |
+
}),
|
| 241 |
+
})
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
One API slice per base URL preserves invalidation behavior and avoids duplicated middleware work.
|
| 245 |
+
|
| 246 |
+
Source: reduxjs/redux-toolkit:docs/rtk-query/api/createApi.mdx
|
| 247 |
+
|
| 248 |
+
### HIGH Forgetting `api.reducer` or `api.middleware`
|
| 249 |
+
|
| 250 |
+
Wrong:
|
| 251 |
+
|
| 252 |
+
```ts
|
| 253 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 254 |
+
|
| 255 |
+
const store = configureStore({
|
| 256 |
+
reducer: {},
|
| 257 |
+
})
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
Correct:
|
| 261 |
+
|
| 262 |
+
```ts
|
| 263 |
+
import { configureStore } from '@reduxjs/toolkit'
|
| 264 |
+
|
| 265 |
+
const store = configureStore({
|
| 266 |
+
reducer: {
|
| 267 |
+
[api.reducerPath]: api.reducer,
|
| 268 |
+
},
|
| 269 |
+
middleware: (getDefaultMiddleware) =>
|
| 270 |
+
getDefaultMiddleware().concat(api.middleware),
|
| 271 |
+
})
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
RTK Query hooks need both the reducer and middleware to manage cache state and request lifecycles.
|
| 275 |
+
|
| 276 |
+
Source: reduxjs/redux-toolkit:docs/tutorials/rtk-query.mdx
|
| 277 |
+
|
| 278 |
+
### MEDIUM Persisting browser API cache by default
|
| 279 |
+
|
| 280 |
+
Wrong:
|
| 281 |
+
|
| 282 |
+
```ts
|
| 283 |
+
const storage = window.localStorage
|
| 284 |
+
|
| 285 |
+
const persistConfig = {
|
| 286 |
+
key: 'root',
|
| 287 |
+
storage,
|
| 288 |
+
}
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
Correct:
|
| 292 |
+
|
| 293 |
+
```ts
|
| 294 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 295 |
+
|
| 296 |
+
const api = createApi({
|
| 297 |
+
reducerPath: 'api',
|
| 298 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
|
| 299 |
+
endpoints: () => ({}),
|
| 300 |
+
})
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
Persisting RTK Query cache in browsers often keeps stale data around longer than users expect; treat persistence as a special case, not the default.
|
| 304 |
+
|
| 305 |
+
Source: reduxjs/redux-toolkit:docs/rtk-query/usage/persistence-and-rehydration.mdx
|
| 306 |
+
|
| 307 |
+
### HIGH Patching cache from components
|
| 308 |
+
|
| 309 |
+
Wrong:
|
| 310 |
+
|
| 311 |
+
```tsx
|
| 312 |
+
import { useEffect } from 'react'
|
| 313 |
+
import { useAppDispatch } from '../../app/hooks'
|
| 314 |
+
|
| 315 |
+
const dispatch = useAppDispatch()
|
| 316 |
+
|
| 317 |
+
useEffect(() => {
|
| 318 |
+
dispatch(api.util.updateQueryData('getPosts', undefined, (draft) => {
|
| 319 |
+
draft.push({ id: 'p3', title: 'Patched from component' })
|
| 320 |
+
}))
|
| 321 |
+
}, [dispatch])
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
Correct:
|
| 325 |
+
|
| 326 |
+
```ts
|
| 327 |
+
updatePostTitle: build.mutation<Post, Pick<Post, 'id' | 'title'>>({
|
| 328 |
+
query: ({ id, title }) => ({
|
| 329 |
+
url: `posts/${id}`,
|
| 330 |
+
method: 'PATCH',
|
| 331 |
+
body: { title },
|
| 332 |
+
}),
|
| 333 |
+
async onQueryStarted({ id, title }, { dispatch, queryFulfilled }) {
|
| 334 |
+
const patch = dispatch(
|
| 335 |
+
api.util.updateQueryData('getPosts', undefined, (draft) => {
|
| 336 |
+
const post = draft.find((item) => item.id === id)
|
| 337 |
+
if (post) {
|
| 338 |
+
post.title = title
|
| 339 |
+
}
|
| 340 |
+
}),
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
try {
|
| 344 |
+
await queryFulfilled
|
| 345 |
+
} catch {
|
| 346 |
+
patch.undo()
|
| 347 |
+
}
|
| 348 |
+
},
|
| 349 |
+
})
|
| 350 |
+
```
|
| 351 |
+
|
| 352 |
+
Component-level cache patches drift away from the mutation lifecycle that should own them.
|
| 353 |
+
|
| 354 |
+
Source: reduxjs/redux-toolkit:docs/rtk-query/usage/manual-cache-updates.mdx
|
| 355 |
+
|
| 356 |
+
### HIGH Expecting invalidation to refetch unsubscribed queries
|
| 357 |
+
|
| 358 |
+
Wrong:
|
| 359 |
+
|
| 360 |
+
```ts
|
| 361 |
+
import { api } from './api'
|
| 362 |
+
import { store } from './store'
|
| 363 |
+
|
| 364 |
+
const subscription = store.dispatch(api.endpoints.getPosts.initiate())
|
| 365 |
+
subscription.unsubscribe()
|
| 366 |
+
store.dispatch(api.util.invalidateTags(['Post']))
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
Correct:
|
| 370 |
+
|
| 371 |
+
```ts
|
| 372 |
+
import { api } from './api'
|
| 373 |
+
import { store } from './store'
|
| 374 |
+
|
| 375 |
+
store.dispatch(api.endpoints.getPosts.initiate())
|
| 376 |
+
store.dispatch(api.util.invalidateTags(['Post']))
|
| 377 |
+
```
|
| 378 |
+
|
| 379 |
+
Invalidation only refetches actively subscribed queries; if no component is using that cache entry, RTK Query drops it and fetches again next time it is needed.
|
| 380 |
+
|
| 381 |
+
Source: reduxjs/redux-toolkit:docs/rtk-query/usage/automated-refetching.mdx
|
| 382 |
+
|
| 383 |
+
## References
|
| 384 |
+
|
| 385 |
+
- [Endpoint lifecycle details and cache tradeoffs](references/endpoint-lifecycle.md)
|
node_modules/@reduxjs/toolkit/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Endpoint Lifecycle
|
| 2 |
+
|
| 3 |
+
## Invalidation rule
|
| 4 |
+
|
| 5 |
+
When a mutation invalidates tags:
|
| 6 |
+
|
| 7 |
+
- active subscribers refetch
|
| 8 |
+
- inactive cache entries are removed
|
| 9 |
+
- removed entries fetch again only when something subscribes later
|
| 10 |
+
|
| 11 |
+
That behavior is deliberate; invalidation is not a background "refresh everything" switch.
|
| 12 |
+
|
| 13 |
+
## Document cache tradeoff
|
| 14 |
+
|
| 15 |
+
RTK Query is a document cache, not a normalized entity graph cache.
|
| 16 |
+
|
| 17 |
+
Use RTK Query by default when:
|
| 18 |
+
|
| 19 |
+
- the data comes from request/response APIs
|
| 20 |
+
- document caching is acceptable
|
| 21 |
+
- tag invalidation and endpoint lifecycles solve the problem
|
| 22 |
+
|
| 23 |
+
Reach for a different tool when:
|
| 24 |
+
|
| 25 |
+
- the real requirement is a normalized graph cache
|
| 26 |
+
- the stack already has a domain-specific normalized client that fits better
|
| 27 |
+
|
| 28 |
+
If normalized caching is mandatory and no better library is already in the stack, a slice plus thunk flow may be the fallback.
|
| 29 |
+
|
| 30 |
+
## Useful endpoint options
|
| 31 |
+
|
| 32 |
+
- `providesTags`: tell RTK Query what cache entries this query represents
|
| 33 |
+
- `invalidatesTags`: tell RTK Query what a mutation dirties
|
| 34 |
+
- `onQueryStarted`: optimistic and pessimistic updates tied to a request
|
| 35 |
+
- `onCacheEntryAdded`: long-lived subscriptions such as streaming data
|
| 36 |
+
- `keepUnusedDataFor`: how long inactive cache entries stay around
|
node_modules/@reduxjs/toolkit/skills/model-redux-state/build-slices-and-selectors/SKILL.md
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: model-redux-state/build-slices-and-selectors
|
| 3 |
+
description: >
|
| 4 |
+
Use this when authoring or refactoring slices with createSlice, selectors,
|
| 5 |
+
create.asyncThunk, entity adapters, or lazy reducer injection. Covers
|
| 6 |
+
Immer-backed mutation syntax, slice selectors, getSelectors, injectInto,
|
| 7 |
+
withLazyLoadedSlices, and current RTK 2 slice patterns.
|
| 8 |
+
type: core
|
| 9 |
+
library: "@reduxjs/toolkit"
|
| 10 |
+
library_version: "2.11.2"
|
| 11 |
+
requires:
|
| 12 |
+
- model-redux-state/design-state-ownership
|
| 13 |
+
sources:
|
| 14 |
+
- "reduxjs/redux-toolkit:docs/api/createSlice.mdx"
|
| 15 |
+
- "reduxjs/redux-toolkit:docs/api/combineSlices.mdx"
|
| 16 |
+
- "reduxjs/redux-toolkit:docs/api/createEntityAdapter.mdx"
|
| 17 |
+
- "reduxjs/redux-toolkit:docs/usage/immer-reducers.md"
|
| 18 |
+
- "reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md"
|
| 19 |
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# Build Slices And Selectors
|
| 23 |
+
|
| 24 |
+
## Setup
|
| 25 |
+
|
| 26 |
+
```ts
|
| 27 |
+
// file: src/app/createAppSlice.ts
|
| 28 |
+
import { asyncThunkCreator, buildCreateSlice } from '@reduxjs/toolkit'
|
| 29 |
+
|
| 30 |
+
export const createAppSlice = buildCreateSlice({
|
| 31 |
+
creators: { asyncThunk: asyncThunkCreator },
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
// file: src/features/posts/postsSlice.ts
|
| 35 |
+
import { createSelector } from '@reduxjs/toolkit'
|
| 36 |
+
import { createAppSlice } from '../../app/createAppSlice'
|
| 37 |
+
|
| 38 |
+
type PostsState = {
|
| 39 |
+
items: { id: string; title: string; published: boolean }[]
|
| 40 |
+
status: 'idle' | 'pending' | 'succeeded' | 'failed'
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
const initialState: PostsState = {
|
| 44 |
+
items: [],
|
| 45 |
+
status: 'idle',
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
export const postsSlice = createAppSlice({
|
| 49 |
+
name: 'posts',
|
| 50 |
+
initialState,
|
| 51 |
+
reducers: (create) => ({
|
| 52 |
+
postAdded: create.reducer<{ id: string; title: string }>((state, action) => {
|
| 53 |
+
state.items.push({ ...action.payload, published: false })
|
| 54 |
+
}),
|
| 55 |
+
fetchPosts: create.asyncThunk(
|
| 56 |
+
async () => {
|
| 57 |
+
const response = await fetch('/api/posts')
|
| 58 |
+
return (await response.json()) as { id: string; title: string; published: boolean }[]
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
pending: (state) => {
|
| 62 |
+
state.status = 'pending'
|
| 63 |
+
},
|
| 64 |
+
fulfilled: (state, action) => {
|
| 65 |
+
state.status = 'succeeded'
|
| 66 |
+
state.items = action.payload
|
| 67 |
+
},
|
| 68 |
+
rejected: (state) => {
|
| 69 |
+
state.status = 'failed'
|
| 70 |
+
},
|
| 71 |
+
},
|
| 72 |
+
),
|
| 73 |
+
}),
|
| 74 |
+
selectors: {
|
| 75 |
+
selectPosts: (state) => state.items,
|
| 76 |
+
selectPublishedPosts: createSelector(
|
| 77 |
+
[(state: PostsState) => state.items],
|
| 78 |
+
(items) => items.filter((post) => post.published),
|
| 79 |
+
),
|
| 80 |
+
},
|
| 81 |
+
})
|
| 82 |
+
|
| 83 |
+
export const { postAdded, fetchPosts } = postsSlice.actions
|
| 84 |
+
export const { selectPosts, selectPublishedPosts } = postsSlice.selectors
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## Core Patterns
|
| 88 |
+
|
| 89 |
+
### Use mutating logic inside slice reducers
|
| 90 |
+
|
| 91 |
+
```ts
|
| 92 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 93 |
+
|
| 94 |
+
const todosSlice = createSlice({
|
| 95 |
+
name: 'todos',
|
| 96 |
+
initialState: [] as { id: string; text: string; done: boolean }[],
|
| 97 |
+
reducers: {
|
| 98 |
+
todoAdded(state, action: { payload: { id: string; text: string } }) {
|
| 99 |
+
state.push({ ...action.payload, done: false })
|
| 100 |
+
},
|
| 101 |
+
todoToggled(state, action: { payload: { id: string } }) {
|
| 102 |
+
const todo = state.find((item) => item.id === action.payload.id)
|
| 103 |
+
if (todo) {
|
| 104 |
+
todo.done = !todo.done
|
| 105 |
+
}
|
| 106 |
+
},
|
| 107 |
+
},
|
| 108 |
+
})
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
Immer is the default inside `createSlice`; write the reducer logic directly instead of copying arrays and objects by hand.
|
| 112 |
+
|
| 113 |
+
### Define selectors in the slice when they belong to the slice
|
| 114 |
+
|
| 115 |
+
```ts
|
| 116 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 117 |
+
|
| 118 |
+
const counterSlice = createSlice({
|
| 119 |
+
name: 'counter',
|
| 120 |
+
initialState: { value: 0 },
|
| 121 |
+
reducers: {
|
| 122 |
+
increment(state) {
|
| 123 |
+
state.value += 1
|
| 124 |
+
},
|
| 125 |
+
},
|
| 126 |
+
selectors: {
|
| 127 |
+
selectValue: (state) => state.value,
|
| 128 |
+
selectIsPositive: (state) => state.value > 0,
|
| 129 |
+
},
|
| 130 |
+
})
|
| 131 |
+
|
| 132 |
+
const { selectValue, selectIsPositive } = counterSlice.selectors
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Slice selectors keep state-location knowledge next to the slice.
|
| 136 |
+
|
| 137 |
+
### Use `create.asyncThunk` when the async lifecycle belongs to the slice
|
| 138 |
+
|
| 139 |
+
```ts
|
| 140 |
+
import { asyncThunkCreator, buildCreateSlice } from '@reduxjs/toolkit'
|
| 141 |
+
|
| 142 |
+
const createAppSlice = buildCreateSlice({
|
| 143 |
+
creators: { asyncThunk: asyncThunkCreator },
|
| 144 |
+
})
|
| 145 |
+
|
| 146 |
+
const usersSlice = createAppSlice({
|
| 147 |
+
name: 'users',
|
| 148 |
+
initialState: { items: [] as { id: string; name: string }[], status: 'idle' as 'idle' | 'pending' | 'failed' },
|
| 149 |
+
reducers: (create) => ({
|
| 150 |
+
fetchUsers: create.asyncThunk(
|
| 151 |
+
async () => {
|
| 152 |
+
const response = await fetch('/api/users')
|
| 153 |
+
return (await response.json()) as { id: string; name: string }[]
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
pending: (state) => {
|
| 157 |
+
state.status = 'pending'
|
| 158 |
+
},
|
| 159 |
+
fulfilled: (state, action) => {
|
| 160 |
+
state.status = 'idle'
|
| 161 |
+
state.items = action.payload
|
| 162 |
+
},
|
| 163 |
+
rejected: (state) => {
|
| 164 |
+
state.status = 'failed'
|
| 165 |
+
},
|
| 166 |
+
},
|
| 167 |
+
),
|
| 168 |
+
}),
|
| 169 |
+
})
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
Use this when the async lifecycle handlers naturally live with the slice; otherwise regular `createAsyncThunk` is still fine.
|
| 173 |
+
|
| 174 |
+
### Use entity adapters and lazy injection for scalable slices
|
| 175 |
+
|
| 176 |
+
```ts
|
| 177 |
+
import {
|
| 178 |
+
combineSlices,
|
| 179 |
+
createEntityAdapter,
|
| 180 |
+
createSlice,
|
| 181 |
+
} from '@reduxjs/toolkit'
|
| 182 |
+
|
| 183 |
+
type Book = { bookId: string; title: string }
|
| 184 |
+
|
| 185 |
+
const booksAdapter = createEntityAdapter<Book>({
|
| 186 |
+
selectId: (book) => book.bookId,
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
const booksSlice = createSlice({
|
| 190 |
+
name: 'books',
|
| 191 |
+
initialState: booksAdapter.getInitialState(),
|
| 192 |
+
reducers: {
|
| 193 |
+
booksReceived: booksAdapter.setAll,
|
| 194 |
+
},
|
| 195 |
+
})
|
| 196 |
+
|
| 197 |
+
export interface LazyLoadedSlices {}
|
| 198 |
+
|
| 199 |
+
export const rootReducer =
|
| 200 |
+
combineSlices().withLazyLoadedSlices<LazyLoadedSlices>()
|
| 201 |
+
|
| 202 |
+
declare module './rootReducer' {
|
| 203 |
+
export interface LazyLoadedSlices {}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
const injectedBooksSlice = booksSlice.injectInto(rootReducer)
|
| 207 |
+
|
| 208 |
+
const selectors = booksAdapter.getSelectors(
|
| 209 |
+
(state: ReturnType<typeof rootReducer.selector.original>) =>
|
| 210 |
+
injectedBooksSlice.selectSlice(state),
|
| 211 |
+
)
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
Entity adapters standardize normalized collections, and `injectInto` lets a slice stay aware of its injected location.
|
| 215 |
+
|
| 216 |
+
## Common Mistakes
|
| 217 |
+
|
| 218 |
+
### CRITICAL Using mutating logic outside slice reducers
|
| 219 |
+
|
| 220 |
+
Wrong:
|
| 221 |
+
|
| 222 |
+
```ts
|
| 223 |
+
type Todo = { id: string; text: string }
|
| 224 |
+
|
| 225 |
+
export function addTodo(todos: Todo[], todo: Todo) {
|
| 226 |
+
todos.push(todo)
|
| 227 |
+
return todos
|
| 228 |
+
}
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
Correct:
|
| 232 |
+
|
| 233 |
+
```ts
|
| 234 |
+
type Todo = { id: string; text: string }
|
| 235 |
+
|
| 236 |
+
const todosSlice = createSlice({
|
| 237 |
+
name: 'todos',
|
| 238 |
+
initialState: [] as Todo[],
|
| 239 |
+
reducers: {
|
| 240 |
+
todoAdded(state, action: { payload: Todo }) {
|
| 241 |
+
state.push(action.payload)
|
| 242 |
+
},
|
| 243 |
+
},
|
| 244 |
+
})
|
| 245 |
+
```
|
| 246 |
+
|
| 247 |
+
Mutation syntax is only safe inside Immer-backed reducer contexts such as `createSlice` and `createReducer`.
|
| 248 |
+
|
| 249 |
+
Source: reduxjs/redux-toolkit:docs/usage/immer-reducers.md
|
| 250 |
+
|
| 251 |
+
### HIGH Writing hand-written switch reducers as the default
|
| 252 |
+
|
| 253 |
+
Wrong:
|
| 254 |
+
|
| 255 |
+
```ts
|
| 256 |
+
export default function todosReducer(state = initialState, action: { type: string; payload?: Todo }) {
|
| 257 |
+
switch (action.type) {
|
| 258 |
+
case 'todos/todoAdded':
|
| 259 |
+
return state.concat(action.payload as Todo)
|
| 260 |
+
default:
|
| 261 |
+
return state
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
Correct:
|
| 267 |
+
|
| 268 |
+
```ts
|
| 269 |
+
const todosSlice = createSlice({
|
| 270 |
+
name: 'todos',
|
| 271 |
+
initialState,
|
| 272 |
+
reducers: {
|
| 273 |
+
todoAdded(state, action: { payload: Todo }) {
|
| 274 |
+
state.push(action.payload)
|
| 275 |
+
},
|
| 276 |
+
},
|
| 277 |
+
})
|
| 278 |
+
```
|
| 279 |
+
|
| 280 |
+
Hand-written reducers are an escape hatch for proven bottlenecks, not the normal thing an agent should generate in RTK code.
|
| 281 |
+
|
| 282 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx
|
| 283 |
+
|
| 284 |
+
### HIGH Writing RTK 1.x object syntax for `extraReducers`
|
| 285 |
+
|
| 286 |
+
Wrong:
|
| 287 |
+
|
| 288 |
+
```ts
|
| 289 |
+
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
|
| 290 |
+
|
| 291 |
+
const initialState = { items: [] as { id: string; title: string }[] }
|
| 292 |
+
|
| 293 |
+
const fetchPosts = createAsyncThunk('posts/fetch', async () => {
|
| 294 |
+
const response = await fetch('/api/posts')
|
| 295 |
+
return (await response.json()) as { id: string; title: string }[]
|
| 296 |
+
})
|
| 297 |
+
|
| 298 |
+
const postsSlice = createSlice({
|
| 299 |
+
name: 'posts',
|
| 300 |
+
initialState,
|
| 301 |
+
reducers: {},
|
| 302 |
+
extraReducers: {
|
| 303 |
+
[fetchPosts.fulfilled.type]: (state, action) => {
|
| 304 |
+
state.items = action.payload
|
| 305 |
+
},
|
| 306 |
+
},
|
| 307 |
+
})
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
Correct:
|
| 311 |
+
|
| 312 |
+
```ts
|
| 313 |
+
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
|
| 314 |
+
|
| 315 |
+
const initialState = { items: [] as { id: string; title: string }[] }
|
| 316 |
+
|
| 317 |
+
const fetchPosts = createAsyncThunk('posts/fetch', async () => {
|
| 318 |
+
const response = await fetch('/api/posts')
|
| 319 |
+
return (await response.json()) as { id: string; title: string }[]
|
| 320 |
+
})
|
| 321 |
+
|
| 322 |
+
const postsSlice = createSlice({
|
| 323 |
+
name: 'posts',
|
| 324 |
+
initialState,
|
| 325 |
+
reducers: {},
|
| 326 |
+
extraReducers: (builder) => {
|
| 327 |
+
builder.addCase(fetchPosts.fulfilled, (state, action) => {
|
| 328 |
+
state.items = action.payload
|
| 329 |
+
})
|
| 330 |
+
},
|
| 331 |
+
})
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
RTK 2 removed the object form; agents trained on RTK 1.x still generate it.
|
| 335 |
+
|
| 336 |
+
Source: reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md
|
| 337 |
+
|
| 338 |
+
### HIGH Assuming `entity.id` exists for every collection
|
| 339 |
+
|
| 340 |
+
Wrong:
|
| 341 |
+
|
| 342 |
+
```ts
|
| 343 |
+
type Book = { bookId: string; title: string }
|
| 344 |
+
|
| 345 |
+
const booksAdapter = createEntityAdapter<Book>()
|
| 346 |
+
```
|
| 347 |
+
|
| 348 |
+
Correct:
|
| 349 |
+
|
| 350 |
+
```ts
|
| 351 |
+
type Book = { bookId: string; title: string }
|
| 352 |
+
|
| 353 |
+
const booksAdapter = createEntityAdapter<Book>({
|
| 354 |
+
selectId: (book) => book.bookId,
|
| 355 |
+
})
|
| 356 |
+
```
|
| 357 |
+
|
| 358 |
+
Adapters default to `entity.id`; collections keyed by another field must provide `selectId`.
|
| 359 |
+
|
| 360 |
+
Source: reduxjs/redux-toolkit:docs/api/createEntityAdapter.mdx
|
| 361 |
+
|
| 362 |
+
## References
|
| 363 |
+
|
| 364 |
+
- [Slice selectors, async creators, and lazy injection details](references/slice-patterns.md)
|
node_modules/@reduxjs/toolkit/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Slice Patterns
|
| 2 |
+
|
| 3 |
+
## `getSelectors` for alternate mounting points
|
| 4 |
+
|
| 5 |
+
```ts
|
| 6 |
+
const counterSlice = createSlice({
|
| 7 |
+
name: 'counter',
|
| 8 |
+
initialState: { value: 0 },
|
| 9 |
+
reducers: {},
|
| 10 |
+
selectors: {
|
| 11 |
+
selectValue: (state) => state.value,
|
| 12 |
+
},
|
| 13 |
+
})
|
| 14 |
+
|
| 15 |
+
export const { selectValue } = counterSlice.getSelectors(
|
| 16 |
+
(state: { customCounter: { value: number } }) => state.customCounter,
|
| 17 |
+
)
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
Use `getSelectors` when the slice is not mounted at its default `reducerPath`.
|
| 21 |
+
|
| 22 |
+
## `withLazyLoadedSlices` and `injectInto`
|
| 23 |
+
|
| 24 |
+
```ts
|
| 25 |
+
import { combineSlices, createSlice, type WithSlice } from '@reduxjs/toolkit'
|
| 26 |
+
|
| 27 |
+
const staticSlice = createSlice({
|
| 28 |
+
name: 'static',
|
| 29 |
+
initialState: { ready: true },
|
| 30 |
+
reducers: {},
|
| 31 |
+
})
|
| 32 |
+
|
| 33 |
+
export interface LazyLoadedSlices {}
|
| 34 |
+
|
| 35 |
+
export const rootReducer =
|
| 36 |
+
combineSlices(staticSlice).withLazyLoadedSlices<LazyLoadedSlices>()
|
| 37 |
+
|
| 38 |
+
const lazySlice = createSlice({
|
| 39 |
+
name: 'lazy',
|
| 40 |
+
initialState: { value: 0 },
|
| 41 |
+
reducers: {
|
| 42 |
+
increment(state) {
|
| 43 |
+
state.value += 1
|
| 44 |
+
},
|
| 45 |
+
},
|
| 46 |
+
})
|
| 47 |
+
|
| 48 |
+
declare module '../rootReducer' {
|
| 49 |
+
export interface LazyLoadedSlices extends WithSlice<typeof lazySlice> {}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
export const injectedLazySlice = lazySlice.injectInto(rootReducer)
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
This keeps RootState types aware of reducers that will be injected later.
|
| 56 |
+
|
| 57 |
+
## Selector caveat
|
| 58 |
+
|
| 59 |
+
If a selector depends on caller-specific arguments and must be memoized per caller, prefer a selector factory outside `createSlice.selectors`. `createSlice.selectors` gives you one selector instance, not a selector factory.
|
node_modules/@reduxjs/toolkit/skills/model-redux-state/design-state-ownership/SKILL.md
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: model-redux-state/design-state-ownership
|
| 3 |
+
description: >
|
| 4 |
+
Use this when deciding whether data belongs in Redux, component state, router
|
| 5 |
+
state, or another external source. Covers state ownership, authority
|
| 6 |
+
boundaries, slice sizing, and when to move or split data as the app evolves.
|
| 7 |
+
type: core
|
| 8 |
+
library: "@reduxjs/toolkit"
|
| 9 |
+
library_version: "2.11.2"
|
| 10 |
+
sources:
|
| 11 |
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
| 12 |
+
- "reduxjs/redux:docs/tutorials/essentials/part-2-app-structure.md"
|
| 13 |
+
- "reduxjs/redux:docs/tutorials/essentials/part-4-using-data.md"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# Design State Ownership
|
| 17 |
+
|
| 18 |
+
## Setup
|
| 19 |
+
|
| 20 |
+
```tsx
|
| 21 |
+
import { useState } from 'react'
|
| 22 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 23 |
+
import { useAppDispatch } from '../../app/hooks'
|
| 24 |
+
|
| 25 |
+
const postsSlice = createSlice({
|
| 26 |
+
name: 'posts',
|
| 27 |
+
initialState: [] as { id: string; title: string; content: string }[],
|
| 28 |
+
reducers: {
|
| 29 |
+
postAdded(
|
| 30 |
+
state,
|
| 31 |
+
action: { payload: { id: string; title: string; content: string } },
|
| 32 |
+
) {
|
| 33 |
+
state.push(action.payload)
|
| 34 |
+
},
|
| 35 |
+
},
|
| 36 |
+
})
|
| 37 |
+
|
| 38 |
+
const { postAdded } = postsSlice.actions
|
| 39 |
+
|
| 40 |
+
export function AddPostForm() {
|
| 41 |
+
const [title, setTitle] = useState('')
|
| 42 |
+
const [content, setContent] = useState('')
|
| 43 |
+
const dispatch = useAppDispatch()
|
| 44 |
+
|
| 45 |
+
return (
|
| 46 |
+
<form
|
| 47 |
+
onSubmit={(event) => {
|
| 48 |
+
event.preventDefault()
|
| 49 |
+
dispatch(postAdded({ id: 'p1', title, content }))
|
| 50 |
+
}}
|
| 51 |
+
>
|
| 52 |
+
<input value={title} onChange={(event) => setTitle(event.target.value)} />
|
| 53 |
+
<textarea
|
| 54 |
+
value={content}
|
| 55 |
+
onChange={(event) => setContent(event.target.value)}
|
| 56 |
+
/>
|
| 57 |
+
<button type="submit">Save</button>
|
| 58 |
+
</form>
|
| 59 |
+
)
|
| 60 |
+
}
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## Core Patterns
|
| 64 |
+
|
| 65 |
+
### Keep editable form state local until the user commits it
|
| 66 |
+
|
| 67 |
+
```tsx
|
| 68 |
+
import { useState } from 'react'
|
| 69 |
+
import { useAppDispatch } from '../../app/hooks'
|
| 70 |
+
import { profileSaved } from './profileSlice'
|
| 71 |
+
|
| 72 |
+
export function ProfileForm() {
|
| 73 |
+
const [displayName, setDisplayName] = useState('Lenz')
|
| 74 |
+
const dispatch = useAppDispatch()
|
| 75 |
+
|
| 76 |
+
return (
|
| 77 |
+
<form
|
| 78 |
+
onSubmit={(event) => {
|
| 79 |
+
event.preventDefault()
|
| 80 |
+
dispatch(profileSaved({ displayName }))
|
| 81 |
+
}}
|
| 82 |
+
>
|
| 83 |
+
<input
|
| 84 |
+
value={displayName}
|
| 85 |
+
onChange={(event) => setDisplayName(event.target.value)}
|
| 86 |
+
/>
|
| 87 |
+
<button type="submit">Save</button>
|
| 88 |
+
</form>
|
| 89 |
+
)
|
| 90 |
+
}
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Prefer Redux for shared, durable app state, not every keystroke.
|
| 94 |
+
|
| 95 |
+
### Keep URL state with the router and combine it at the edge
|
| 96 |
+
|
| 97 |
+
```tsx
|
| 98 |
+
import { createSelector } from '@reduxjs/toolkit'
|
| 99 |
+
import { useSearchParams } from 'react-router-dom'
|
| 100 |
+
import { useAppSelector } from '../../app/hooks'
|
| 101 |
+
|
| 102 |
+
type RootState = {
|
| 103 |
+
posts: {
|
| 104 |
+
items: { id: string; title: string; published: boolean }[]
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
const selectPosts = (state: RootState) => state.posts.items
|
| 109 |
+
|
| 110 |
+
const selectVisiblePosts = createSelector(
|
| 111 |
+
[selectPosts, (_state: RootState, filter: string) => filter],
|
| 112 |
+
(posts, filter) =>
|
| 113 |
+
filter === 'published'
|
| 114 |
+
? posts.filter((post) => post.published)
|
| 115 |
+
: posts,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
export function PostsList() {
|
| 119 |
+
const [searchParams] = useSearchParams()
|
| 120 |
+
const filter = searchParams.get('filter') ?? 'all'
|
| 121 |
+
const posts = useAppSelector((state) => selectVisiblePosts(state, filter))
|
| 122 |
+
|
| 123 |
+
return <div>{posts.length}</div>
|
| 124 |
+
}
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
If the router already owns a piece of state, pass it into selectors or combine it in the component instead of syncing it into Redux.
|
| 128 |
+
|
| 129 |
+
### Re-size slices when access patterns change
|
| 130 |
+
|
| 131 |
+
```ts
|
| 132 |
+
import { combineReducers, createSlice } from '@reduxjs/toolkit'
|
| 133 |
+
|
| 134 |
+
const authSlice = createSlice({
|
| 135 |
+
name: 'auth',
|
| 136 |
+
initialState: { userId: null as string | null },
|
| 137 |
+
reducers: {},
|
| 138 |
+
})
|
| 139 |
+
|
| 140 |
+
const postsSlice = createSlice({
|
| 141 |
+
name: 'posts',
|
| 142 |
+
initialState: { items: [] as { id: string; title: string }[] },
|
| 143 |
+
reducers: {},
|
| 144 |
+
})
|
| 145 |
+
|
| 146 |
+
export const rootReducer = combineReducers({
|
| 147 |
+
auth: authSlice.reducer,
|
| 148 |
+
posts: postsSlice.reducer,
|
| 149 |
+
})
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
Revisit slice size over time; unrelated data should split apart, and data constantly stitched together in every component may belong closer together.
|
| 153 |
+
|
| 154 |
+
## Common Mistakes
|
| 155 |
+
|
| 156 |
+
### MEDIUM Putting form editing state in Redux
|
| 157 |
+
|
| 158 |
+
Wrong:
|
| 159 |
+
|
| 160 |
+
```tsx
|
| 161 |
+
import { useAppSelector } from '../../app/hooks'
|
| 162 |
+
|
| 163 |
+
const selectDraftTitle = (state: { draft: { title: string } }) => state.draft.title
|
| 164 |
+
|
| 165 |
+
const title = useAppSelector(selectDraftTitle)
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
Correct:
|
| 169 |
+
|
| 170 |
+
```tsx
|
| 171 |
+
const [title, setTitle] = useState('')
|
| 172 |
+
|
| 173 |
+
<input value={title} onChange={(event) => setTitle(event.target.value)} />
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
Per-keystroke dispatching adds global complexity for data that usually lives in one component tree.
|
| 177 |
+
|
| 178 |
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
| 179 |
+
|
| 180 |
+
### HIGH Synchronizing router or URL state into Redux
|
| 181 |
+
|
| 182 |
+
Wrong:
|
| 183 |
+
|
| 184 |
+
```tsx
|
| 185 |
+
import { useEffect } from 'react'
|
| 186 |
+
import { useSearchParams } from 'react-router-dom'
|
| 187 |
+
import { useAppDispatch } from '../../app/hooks'
|
| 188 |
+
|
| 189 |
+
function PostsPage() {
|
| 190 |
+
const [searchParams] = useSearchParams()
|
| 191 |
+
const dispatch = useAppDispatch()
|
| 192 |
+
|
| 193 |
+
useEffect(() => {
|
| 194 |
+
dispatch(filterChanged(searchParams.get('filter') ?? 'all'))
|
| 195 |
+
}, [dispatch, searchParams])
|
| 196 |
+
|
| 197 |
+
return null
|
| 198 |
+
}
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
Correct:
|
| 202 |
+
|
| 203 |
+
```tsx
|
| 204 |
+
const filter = searchParams.get('filter') ?? 'all'
|
| 205 |
+
const posts = useAppSelector((state) => selectVisiblePosts(state, filter))
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
URL state already has an authoritative owner; duplicating it into Redux creates two sources of truth.
|
| 209 |
+
|
| 210 |
+
Source: maintainer interview
|
| 211 |
+
|
| 212 |
+
### HIGH Naming state after components
|
| 213 |
+
|
| 214 |
+
Wrong:
|
| 215 |
+
|
| 216 |
+
```ts
|
| 217 |
+
import { combineReducers } from '@reduxjs/toolkit'
|
| 218 |
+
|
| 219 |
+
const loginReducer = (state = { open: false }) => state
|
| 220 |
+
const postsReducer = (state = [] as { id: string; title: string }[]) => state
|
| 221 |
+
|
| 222 |
+
const rootReducer = combineReducers({
|
| 223 |
+
loginScreen: loginReducer,
|
| 224 |
+
postsList: postsReducer,
|
| 225 |
+
})
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
Correct:
|
| 229 |
+
|
| 230 |
+
```ts
|
| 231 |
+
import { combineReducers } from '@reduxjs/toolkit'
|
| 232 |
+
|
| 233 |
+
const authReducer = (state = { userId: null as string | null }) => state
|
| 234 |
+
const postsReducer = (state = [] as { id: string; title: string }[]) => state
|
| 235 |
+
|
| 236 |
+
const rootReducer = combineReducers({
|
| 237 |
+
auth: authReducer,
|
| 238 |
+
posts: postsReducer,
|
| 239 |
+
})
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
Store keys should describe data or domain concepts, not the current component tree.
|
| 243 |
+
|
| 244 |
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
| 245 |
+
|
| 246 |
+
### MEDIUM Letting slice boundaries fossilize
|
| 247 |
+
|
| 248 |
+
Wrong:
|
| 249 |
+
|
| 250 |
+
```ts
|
| 251 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 252 |
+
|
| 253 |
+
type Post = { id: string; title: string }
|
| 254 |
+
type AppNotification = { id: string; message: string }
|
| 255 |
+
|
| 256 |
+
const appSlice = createSlice({
|
| 257 |
+
name: 'app',
|
| 258 |
+
initialState: {
|
| 259 |
+
auth: { userId: null as string | null },
|
| 260 |
+
posts: [] as Post[],
|
| 261 |
+
notifications: [] as AppNotification[],
|
| 262 |
+
},
|
| 263 |
+
reducers: {},
|
| 264 |
+
})
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
Correct:
|
| 268 |
+
|
| 269 |
+
```ts
|
| 270 |
+
import { createSlice } from '@reduxjs/toolkit'
|
| 271 |
+
|
| 272 |
+
type Post = { id: string; title: string }
|
| 273 |
+
|
| 274 |
+
const authSlice = createSlice({
|
| 275 |
+
name: 'auth',
|
| 276 |
+
initialState: { userId: null as string | null },
|
| 277 |
+
reducers: {},
|
| 278 |
+
})
|
| 279 |
+
|
| 280 |
+
const postsSlice = createSlice({
|
| 281 |
+
name: 'posts',
|
| 282 |
+
initialState: [] as Post[],
|
| 283 |
+
reducers: {},
|
| 284 |
+
})
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
When unrelated data is welded together, every change point gets noisier; split or merge slices as actual access patterns demand.
|
| 288 |
+
|
| 289 |
+
Source: maintainer interview
|
| 290 |
+
|
| 291 |
+
### HIGH Blindly spreading payloads into state
|
| 292 |
+
|
| 293 |
+
Wrong:
|
| 294 |
+
|
| 295 |
+
```ts
|
| 296 |
+
const state = { id: '1', name: 'Lenz' }
|
| 297 |
+
const action = { payload: { id: '2', name: 'Mark', ignored: true } }
|
| 298 |
+
|
| 299 |
+
userLoggedIn(state, action) {
|
| 300 |
+
return { ...state, ...action.payload }
|
| 301 |
+
}
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
Correct:
|
| 305 |
+
|
| 306 |
+
```ts
|
| 307 |
+
const state = { id: '1', name: 'Lenz' }
|
| 308 |
+
const action = { payload: { id: '2', name: 'Mark', ignored: true } }
|
| 309 |
+
|
| 310 |
+
userLoggedIn(state, action) {
|
| 311 |
+
state.id = action.payload.id
|
| 312 |
+
state.name = action.payload.name
|
| 313 |
+
}
|
| 314 |
+
```
|
| 315 |
+
|
| 316 |
+
Reducers should own the slice shape instead of treating payloads as trusted state patches.
|
| 317 |
+
|
| 318 |
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
| 319 |
+
|
| 320 |
+
## References
|
| 321 |
+
|
| 322 |
+
- [State ownership heuristics](references/state-ownership.md)
|
node_modules/@reduxjs/toolkit/skills/model-redux-state/design-state-ownership/references/state-ownership.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# State Ownership Heuristics
|
| 2 |
+
|
| 3 |
+
## Choose the owner, then the tool
|
| 4 |
+
|
| 5 |
+
| Kind of state | Default owner | Typical tool |
|
| 6 |
+
| --- | --- | --- |
|
| 7 |
+
| Editable form fields | Component | `useState` |
|
| 8 |
+
| Shared mutable app data | Redux | Slice state |
|
| 9 |
+
| Server cache | RTK Query | `createApi` |
|
| 10 |
+
| URL, pathname, search params | Router | Router APIs plus selector inputs |
|
| 11 |
+
| Browser-only authority like `localStorage` | External source | Read at boundaries, then dispatch events |
|
| 12 |
+
|
| 13 |
+
## Good reasons to move data into Redux
|
| 14 |
+
|
| 15 |
+
- Multiple distant parts of the UI need the same mutable data.
|
| 16 |
+
- You need time-travel debugging or a stable action history.
|
| 17 |
+
- The reducer should own transitions because they mix old store state with new inputs.
|
| 18 |
+
|
| 19 |
+
## Reasons to keep data out of Redux
|
| 20 |
+
|
| 21 |
+
- Another system already owns it, such as the router.
|
| 22 |
+
- It only matters during editing inside one component tree.
|
| 23 |
+
- It is server cache and RTK Query fits the use case better.
|
| 24 |
+
|
| 25 |
+
## Re-evaluate slice size
|
| 26 |
+
|
| 27 |
+
- If data is constantly stitched together outside reducers, it may belong closer together.
|
| 28 |
+
- If unrelated updates keep touching the same slice, split the slice by domain ownership.
|
node_modules/@reduxjs/toolkit/skills/orchestrate-side-effects/handle-side-effects/SKILL.md
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 3 |
+
description: >
|
| 4 |
+
Use this when choosing between RTK Query, createAsyncThunk, handwritten
|
| 5 |
+
thunks, and createListenerMiddleware. Covers imperative versus reactive
|
| 6 |
+
workflows, listener middleware setup, and keeping side effects out of
|
| 7 |
+
reducers and UI components.
|
| 8 |
+
type: core
|
| 9 |
+
library: "@reduxjs/toolkit"
|
| 10 |
+
library_version: "2.11.2"
|
| 11 |
+
requires:
|
| 12 |
+
- build-modern-redux-apps/redux-dataflow
|
| 13 |
+
sources:
|
| 14 |
+
- "reduxjs/redux-toolkit:docs/api/createAsyncThunk.mdx"
|
| 15 |
+
- "reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx"
|
| 16 |
+
- "reduxjs/redux:docs/style-guide/style-guide.md"
|
| 17 |
+
- "reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md"
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# Handle Side Effects
|
| 21 |
+
|
| 22 |
+
## Setup
|
| 23 |
+
|
| 24 |
+
```ts
|
| 25 |
+
import {
|
| 26 |
+
configureStore,
|
| 27 |
+
createListenerMiddleware,
|
| 28 |
+
createSlice,
|
| 29 |
+
} from '@reduxjs/toolkit'
|
| 30 |
+
|
| 31 |
+
const docsSlice = createSlice({
|
| 32 |
+
name: 'docs',
|
| 33 |
+
initialState: { status: 'idle' as 'idle' | 'saved' },
|
| 34 |
+
reducers: {
|
| 35 |
+
saveStarted(state) {
|
| 36 |
+
state.status = 'idle'
|
| 37 |
+
},
|
| 38 |
+
saveFinished(state) {
|
| 39 |
+
state.status = 'saved'
|
| 40 |
+
},
|
| 41 |
+
},
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
const listenerMiddleware = createListenerMiddleware()
|
| 45 |
+
|
| 46 |
+
export const store = configureStore({
|
| 47 |
+
reducer: {
|
| 48 |
+
docs: docsSlice.reducer,
|
| 49 |
+
},
|
| 50 |
+
middleware: (getDefaultMiddleware) =>
|
| 51 |
+
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
export type RootState = ReturnType<typeof store.getState>
|
| 55 |
+
export type AppDispatch = typeof store.dispatch
|
| 56 |
+
|
| 57 |
+
export const startAppListening =
|
| 58 |
+
listenerMiddleware.startListening.withTypes<RootState, AppDispatch>()
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Core Patterns
|
| 62 |
+
|
| 63 |
+
### Use RTK Query for server cache by default
|
| 64 |
+
|
| 65 |
+
```ts
|
| 66 |
+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
|
| 67 |
+
|
| 68 |
+
type Post = { id: string; title: string }
|
| 69 |
+
|
| 70 |
+
export const api = createApi({
|
| 71 |
+
reducerPath: 'api',
|
| 72 |
+
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
|
| 73 |
+
tagTypes: ['Post'],
|
| 74 |
+
endpoints: (build) => ({
|
| 75 |
+
getPosts: build.query<Post[], void>({
|
| 76 |
+
query: () => 'posts',
|
| 77 |
+
providesTags: ['Post'],
|
| 78 |
+
}),
|
| 79 |
+
}),
|
| 80 |
+
})
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
If the problem is server data that should be cached and re-used, start with RTK Query instead of a thunk.
|
| 84 |
+
|
| 85 |
+
### Use `createAsyncThunk` for imperative workflows
|
| 86 |
+
|
| 87 |
+
```ts
|
| 88 |
+
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
|
| 89 |
+
|
| 90 |
+
type Draft = { title: string }
|
| 91 |
+
|
| 92 |
+
export const draftSaved = createAsyncThunk(
|
| 93 |
+
'drafts/save',
|
| 94 |
+
async (draft: Draft) => {
|
| 95 |
+
const response = await fetch('/api/drafts', {
|
| 96 |
+
method: 'POST',
|
| 97 |
+
headers: { 'Content-Type': 'application/json' },
|
| 98 |
+
body: JSON.stringify(draft),
|
| 99 |
+
})
|
| 100 |
+
|
| 101 |
+
return (await response.json()) as { id: string; title: string }
|
| 102 |
+
},
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
const draftsSlice = createSlice({
|
| 106 |
+
name: 'drafts',
|
| 107 |
+
initialState: { status: 'idle' as 'idle' | 'pending' | 'failed' },
|
| 108 |
+
reducers: {},
|
| 109 |
+
extraReducers: (builder) => {
|
| 110 |
+
builder
|
| 111 |
+
.addCase(draftSaved.pending, (state) => {
|
| 112 |
+
state.status = 'pending'
|
| 113 |
+
})
|
| 114 |
+
.addCase(draftSaved.fulfilled, (state) => {
|
| 115 |
+
state.status = 'idle'
|
| 116 |
+
})
|
| 117 |
+
.addCase(draftSaved.rejected, (state) => {
|
| 118 |
+
state.status = 'failed'
|
| 119 |
+
})
|
| 120 |
+
},
|
| 121 |
+
})
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Use a thunk when you need one imperative async workflow with `dispatch` and `getState`.
|
| 125 |
+
|
| 126 |
+
### Use listener middleware for reactive workflows
|
| 127 |
+
|
| 128 |
+
```ts
|
| 129 |
+
import { createListenerMiddleware, createSlice } from '@reduxjs/toolkit'
|
| 130 |
+
|
| 131 |
+
const docsSlice = createSlice({
|
| 132 |
+
name: 'docs',
|
| 133 |
+
initialState: { status: 'idle' as 'idle' | 'saved' },
|
| 134 |
+
reducers: {
|
| 135 |
+
saveFinished(state) {
|
| 136 |
+
state.status = 'saved'
|
| 137 |
+
},
|
| 138 |
+
},
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
const notificationsSlice = createSlice({
|
| 142 |
+
name: 'notifications',
|
| 143 |
+
initialState: [] as string[],
|
| 144 |
+
reducers: {
|
| 145 |
+
notificationQueued(state, action: { payload: string }) {
|
| 146 |
+
state.push(action.payload)
|
| 147 |
+
},
|
| 148 |
+
},
|
| 149 |
+
})
|
| 150 |
+
|
| 151 |
+
const listenerMiddleware = createListenerMiddleware()
|
| 152 |
+
|
| 153 |
+
listenerMiddleware.startListening({
|
| 154 |
+
actionCreator: docsSlice.actions.saveFinished,
|
| 155 |
+
effect: async (_action, listenerApi) => {
|
| 156 |
+
listenerApi.dispatch(
|
| 157 |
+
notificationsSlice.actions.notificationQueued('Document saved'),
|
| 158 |
+
)
|
| 159 |
+
},
|
| 160 |
+
})
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Listeners fit workflows that react to future actions or state changes over time instead of driving one imperative request from a single callsite.
|
| 164 |
+
|
| 165 |
+
## Common Mistakes
|
| 166 |
+
|
| 167 |
+
### CRITICAL Running side effects inside reducers
|
| 168 |
+
|
| 169 |
+
Wrong:
|
| 170 |
+
|
| 171 |
+
```ts
|
| 172 |
+
const todosSlice = createSlice({
|
| 173 |
+
name: 'todos',
|
| 174 |
+
initialState: [] as { id: string }[],
|
| 175 |
+
reducers: {
|
| 176 |
+
todoSaved(state, action: { payload: { id: string } }) {
|
| 177 |
+
fetch('/api/todos', { method: 'POST' })
|
| 178 |
+
state.push(action.payload)
|
| 179 |
+
},
|
| 180 |
+
},
|
| 181 |
+
})
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
Correct:
|
| 185 |
+
|
| 186 |
+
```ts
|
| 187 |
+
import { createAsyncThunk } from '@reduxjs/toolkit'
|
| 188 |
+
|
| 189 |
+
const todoSaved = createAsyncThunk('todos/save', async (todo: { id: string }) => {
|
| 190 |
+
await fetch('/api/todos', {
|
| 191 |
+
method: 'POST',
|
| 192 |
+
headers: { 'Content-Type': 'application/json' },
|
| 193 |
+
body: JSON.stringify(todo),
|
| 194 |
+
})
|
| 195 |
+
return todo
|
| 196 |
+
})
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
Reducers must stay pure even when Immer is available.
|
| 200 |
+
|
| 201 |
+
Source: reduxjs/redux:docs/style-guide/style-guide.md
|
| 202 |
+
|
| 203 |
+
### HIGH Using thunks to watch future state changes
|
| 204 |
+
|
| 205 |
+
Wrong:
|
| 206 |
+
|
| 207 |
+
```ts
|
| 208 |
+
export const waitForSave = () => async (
|
| 209 |
+
_dispatch: unknown,
|
| 210 |
+
getState: () => { docs: { status: string } },
|
| 211 |
+
) => {
|
| 212 |
+
while (getState().docs.status !== 'saved') {
|
| 213 |
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
| 214 |
+
}
|
| 215 |
+
}
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
Correct:
|
| 219 |
+
|
| 220 |
+
```ts
|
| 221 |
+
startAppListening({
|
| 222 |
+
predicate: (_action, currentState) => currentState.docs.status === 'saved',
|
| 223 |
+
effect: async () => {
|
| 224 |
+
console.log('Document saved')
|
| 225 |
+
},
|
| 226 |
+
})
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
Polling inside thunks fights the architecture; listener middleware is the reactive tool.
|
| 230 |
+
|
| 231 |
+
Source: reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx
|
| 232 |
+
|
| 233 |
+
### HIGH Appending listener middleware after the default checks
|
| 234 |
+
|
| 235 |
+
Wrong:
|
| 236 |
+
|
| 237 |
+
```ts
|
| 238 |
+
import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit'
|
| 239 |
+
|
| 240 |
+
const reducer = (state = { ready: true }) => state
|
| 241 |
+
const listenerMiddleware = createListenerMiddleware()
|
| 242 |
+
|
| 243 |
+
const store = configureStore({
|
| 244 |
+
reducer,
|
| 245 |
+
middleware: (getDefaultMiddleware) =>
|
| 246 |
+
getDefaultMiddleware().concat(listenerMiddleware.middleware),
|
| 247 |
+
})
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
Correct:
|
| 251 |
+
|
| 252 |
+
```ts
|
| 253 |
+
import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit'
|
| 254 |
+
|
| 255 |
+
const reducer = (state = { ready: true }) => state
|
| 256 |
+
const listenerMiddleware = createListenerMiddleware()
|
| 257 |
+
|
| 258 |
+
const store = configureStore({
|
| 259 |
+
reducer,
|
| 260 |
+
middleware: (getDefaultMiddleware) =>
|
| 261 |
+
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
|
| 262 |
+
})
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
Listener add and remove actions may carry functions, so the listener middleware needs to run before serializability checks.
|
| 266 |
+
|
| 267 |
+
Source: reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx
|
| 268 |
+
|
| 269 |
+
## References
|
| 270 |
+
|
| 271 |
+
- [Listener helpers and decision heuristics](references/listener-workflows.md)
|
node_modules/@reduxjs/toolkit/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Listener Workflows
|
| 2 |
+
|
| 3 |
+
## Decision table
|
| 4 |
+
|
| 5 |
+
| Need | Reach for |
|
| 6 |
+
| --- | --- |
|
| 7 |
+
| Cached server data | RTK Query |
|
| 8 |
+
| One imperative async workflow with `dispatch` / `getState` | `createAsyncThunk` or a thunk |
|
| 9 |
+
| React to later actions or state transitions | `createListenerMiddleware` |
|
| 10 |
+
|
| 11 |
+
A good app often mixes imperative and reactive workflows. The split is by job, not by ideology.
|
| 12 |
+
|
| 13 |
+
## Useful listener helpers
|
| 14 |
+
|
| 15 |
+
- `predicate`: react to any action when a state condition becomes true
|
| 16 |
+
- `condition`: wait until a condition becomes true before continuing
|
| 17 |
+
- `take`: wait for the next matching action
|
| 18 |
+
- `cancelActiveListeners`: cancel older instances of the same workflow
|
| 19 |
+
- `fork`: start a child task
|
| 20 |
+
|
| 21 |
+
## Example: cancel stale work
|
| 22 |
+
|
| 23 |
+
```ts
|
| 24 |
+
startAppListening({
|
| 25 |
+
actionCreator: searchRequested,
|
| 26 |
+
effect: async (action, listenerApi) => {
|
| 27 |
+
listenerApi.cancelActiveListeners()
|
| 28 |
+
await listenerApi.delay(250)
|
| 29 |
+
listenerApi.dispatch(searchStarted(action.payload))
|
| 30 |
+
},
|
| 31 |
+
})
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
This is the kind of long-lived reactive behavior that does not fit a thunk well.
|
node_modules/@reduxjs/toolkit/src/actionCreatorInvariantMiddleware.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Middleware } from 'redux'
|
| 2 |
+
import { isActionCreator as isRTKAction } from './createAction'
|
| 3 |
+
|
| 4 |
+
export interface ActionCreatorInvariantMiddlewareOptions {
|
| 5 |
+
/**
|
| 6 |
+
* The function to identify whether a value is an action creator.
|
| 7 |
+
* The default checks for a function with a static type property and match method.
|
| 8 |
+
*/
|
| 9 |
+
isActionCreator?: (action: unknown) => action is Function & { type?: unknown }
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
export function getMessage(type?: unknown) {
|
| 13 |
+
const splitType = type ? `${type}`.split('/') : []
|
| 14 |
+
const actionName = splitType[splitType.length - 1] || 'actionCreator'
|
| 15 |
+
return `Detected an action creator with type "${
|
| 16 |
+
type || 'unknown'
|
| 17 |
+
}" being dispatched.
|
| 18 |
+
Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.`
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
export function createActionCreatorInvariantMiddleware(
|
| 22 |
+
options: ActionCreatorInvariantMiddlewareOptions = {},
|
| 23 |
+
): Middleware {
|
| 24 |
+
if (process.env.NODE_ENV === 'production') {
|
| 25 |
+
return () => (next) => (action) => next(action)
|
| 26 |
+
}
|
| 27 |
+
const { isActionCreator = isRTKAction } = options
|
| 28 |
+
return () => (next) => (action) => {
|
| 29 |
+
if (isActionCreator(action)) {
|
| 30 |
+
console.warn(getMessage(action.type))
|
| 31 |
+
}
|
| 32 |
+
return next(action)
|
| 33 |
+
}
|
| 34 |
+
}
|
node_modules/@reduxjs/toolkit/src/autoBatchEnhancer.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { StoreEnhancer } from 'redux'
|
| 2 |
+
|
| 3 |
+
export const SHOULD_AUTOBATCH = 'RTK_autoBatch'
|
| 4 |
+
|
| 5 |
+
export const prepareAutoBatched =
|
| 6 |
+
<T>() =>
|
| 7 |
+
(payload: T): { payload: T; meta: unknown } => ({
|
| 8 |
+
payload,
|
| 9 |
+
meta: { [SHOULD_AUTOBATCH]: true },
|
| 10 |
+
})
|
| 11 |
+
|
| 12 |
+
const createQueueWithTimer = (timeout: number) => {
|
| 13 |
+
return (notify: () => void) => {
|
| 14 |
+
setTimeout(notify, timeout)
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const createRafWithFallbackTimer = (
|
| 19 |
+
raf: typeof requestAnimationFrame,
|
| 20 |
+
timeout: number,
|
| 21 |
+
) => {
|
| 22 |
+
return (notify: () => void) => {
|
| 23 |
+
let called = false
|
| 24 |
+
const callback = () => {
|
| 25 |
+
if (called) return
|
| 26 |
+
called = true
|
| 27 |
+
cancelAnimationFrame(rafId)
|
| 28 |
+
clearTimeout(timerId)
|
| 29 |
+
notify()
|
| 30 |
+
}
|
| 31 |
+
const rafId = raf(callback)
|
| 32 |
+
const timerId = setTimeout(callback, timeout)
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
export type AutoBatchOptions =
|
| 37 |
+
| { type: 'tick' }
|
| 38 |
+
| { type: 'timer'; timeout: number }
|
| 39 |
+
| { type: 'raf' }
|
| 40 |
+
| { type: 'callback'; queueNotification: (notify: () => void) => void }
|
| 41 |
+
|
| 42 |
+
/**
|
| 43 |
+
* A Redux store enhancer that watches for "low-priority" actions, and delays
|
| 44 |
+
* notifying subscribers until either the queued callback executes or the
|
| 45 |
+
* next "standard-priority" action is dispatched.
|
| 46 |
+
*
|
| 47 |
+
* This allows dispatching multiple "low-priority" actions in a row with only
|
| 48 |
+
* a single subscriber notification to the UI after the sequence of actions
|
| 49 |
+
* is finished, thus improving UI re-render performance.
|
| 50 |
+
*
|
| 51 |
+
* Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
|
| 52 |
+
* This can be added to `action.meta` manually, or by using the
|
| 53 |
+
* `prepareAutoBatched` helper.
|
| 54 |
+
*
|
| 55 |
+
* By default, it will queue a notification for the end of the event loop tick.
|
| 56 |
+
* However, you can pass several other options to configure the behavior:
|
| 57 |
+
* - `{type: 'tick'}`: queues using `queueMicrotask`
|
| 58 |
+
* - `{type: 'timer', timeout: number}`: queues using `setTimeout`
|
| 59 |
+
* - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
|
| 60 |
+
* - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
|
| 61 |
+
*
|
| 62 |
+
*
|
| 63 |
+
*/
|
| 64 |
+
export const autoBatchEnhancer =
|
| 65 |
+
(options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>
|
| 66 |
+
(next) =>
|
| 67 |
+
(...args) => {
|
| 68 |
+
const store = next(...args)
|
| 69 |
+
|
| 70 |
+
let notifying = true
|
| 71 |
+
let shouldNotifyAtEndOfTick = false
|
| 72 |
+
let notificationQueued = false
|
| 73 |
+
|
| 74 |
+
const listeners = new Set<() => void>()
|
| 75 |
+
|
| 76 |
+
const queueCallback =
|
| 77 |
+
options.type === 'tick'
|
| 78 |
+
? queueMicrotask
|
| 79 |
+
: options.type === 'raf'
|
| 80 |
+
? // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.
|
| 81 |
+
typeof window !== 'undefined' && window.requestAnimationFrame
|
| 82 |
+
? createRafWithFallbackTimer(window.requestAnimationFrame, 100)
|
| 83 |
+
: createQueueWithTimer(10)
|
| 84 |
+
: options.type === 'callback'
|
| 85 |
+
? options.queueNotification
|
| 86 |
+
: createQueueWithTimer(options.timeout)
|
| 87 |
+
|
| 88 |
+
const notifyListeners = () => {
|
| 89 |
+
// We're running at the end of the event loop tick.
|
| 90 |
+
// Run the real listener callbacks to actually update the UI.
|
| 91 |
+
notificationQueued = false
|
| 92 |
+
if (shouldNotifyAtEndOfTick) {
|
| 93 |
+
shouldNotifyAtEndOfTick = false
|
| 94 |
+
listeners.forEach((l) => l())
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
return Object.assign({}, store, {
|
| 99 |
+
// Override the base `store.subscribe` method to keep original listeners
|
| 100 |
+
// from running if we're delaying notifications
|
| 101 |
+
subscribe(listener: () => void) {
|
| 102 |
+
// Each wrapped listener will only call the real listener if
|
| 103 |
+
// the `notifying` flag is currently active when it's called.
|
| 104 |
+
// This lets the base store work as normal, while the actual UI
|
| 105 |
+
// update becomes controlled by this enhancer.
|
| 106 |
+
const wrappedListener: typeof listener = () => notifying && listener()
|
| 107 |
+
const unsubscribe = store.subscribe(wrappedListener)
|
| 108 |
+
listeners.add(listener)
|
| 109 |
+
return () => {
|
| 110 |
+
unsubscribe()
|
| 111 |
+
listeners.delete(listener)
|
| 112 |
+
}
|
| 113 |
+
},
|
| 114 |
+
// Override the base `store.dispatch` method so that we can check actions
|
| 115 |
+
// for the `shouldAutoBatch` flag and determine if batching is active
|
| 116 |
+
dispatch(action: any) {
|
| 117 |
+
try {
|
| 118 |
+
// If the action does _not_ have the `shouldAutoBatch` flag,
|
| 119 |
+
// we resume/continue normal notify-after-each-dispatch behavior
|
| 120 |
+
notifying = !action?.meta?.[SHOULD_AUTOBATCH]
|
| 121 |
+
// If a `notifyListeners` microtask was queued, you can't cancel it.
|
| 122 |
+
// Instead, we set a flag so that it's a no-op when it does run
|
| 123 |
+
shouldNotifyAtEndOfTick = !notifying
|
| 124 |
+
if (shouldNotifyAtEndOfTick) {
|
| 125 |
+
// We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue
|
| 126 |
+
// a microtask to notify listeners at the end of the event loop tick.
|
| 127 |
+
// Make sure we only enqueue this _once_ per tick.
|
| 128 |
+
if (!notificationQueued) {
|
| 129 |
+
notificationQueued = true
|
| 130 |
+
queueCallback(notifyListeners)
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
// Go ahead and process the action as usual, including reducers.
|
| 134 |
+
// If normal notification behavior is enabled, the store will notify
|
| 135 |
+
// all of its own listeners, and the wrapper callbacks above will
|
| 136 |
+
// see `notifying` is true and pass on to the real listener callbacks.
|
| 137 |
+
// If we're "batching" behavior, then the wrapped callbacks will
|
| 138 |
+
// bail out, causing the base store notification behavior to be no-ops.
|
| 139 |
+
return store.dispatch(action)
|
| 140 |
+
} finally {
|
| 141 |
+
// Assume we're back to normal behavior after each action
|
| 142 |
+
notifying = true
|
| 143 |
+
}
|
| 144 |
+
},
|
| 145 |
+
})
|
| 146 |
+
}
|
node_modules/@reduxjs/toolkit/src/combineSlices.ts
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {
|
| 2 |
+
PreloadedStateShapeFromReducersMapObject,
|
| 3 |
+
Reducer,
|
| 4 |
+
StateFromReducersMapObject,
|
| 5 |
+
UnknownAction,
|
| 6 |
+
} from 'redux'
|
| 7 |
+
import { combineReducers } from 'redux'
|
| 8 |
+
import { nanoid } from './nanoid'
|
| 9 |
+
import type {
|
| 10 |
+
Id,
|
| 11 |
+
NonUndefined,
|
| 12 |
+
Tail,
|
| 13 |
+
UnionToIntersection,
|
| 14 |
+
WithOptionalProp,
|
| 15 |
+
} from './tsHelpers'
|
| 16 |
+
import { getOrInsertComputed } from './utils'
|
| 17 |
+
|
| 18 |
+
type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
|
| 19 |
+
reducerPath: ReducerPath
|
| 20 |
+
reducer: Reducer<State, any, PreloadedState>
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
type AnySliceLike = SliceLike<string, any>
|
| 24 |
+
|
| 25 |
+
type SliceLikeReducerPath<A extends AnySliceLike> =
|
| 26 |
+
A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never
|
| 27 |
+
|
| 28 |
+
type SliceLikeState<A extends AnySliceLike> =
|
| 29 |
+
A extends SliceLike<any, infer State, any> ? State : never
|
| 30 |
+
|
| 31 |
+
type SliceLikePreloadedState<A extends AnySliceLike> =
|
| 32 |
+
A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never
|
| 33 |
+
|
| 34 |
+
export type WithSlice<A extends AnySliceLike> = {
|
| 35 |
+
[Path in SliceLikeReducerPath<A>]: SliceLikeState<A>
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
export type WithSlicePreloadedState<A extends AnySliceLike> = {
|
| 39 |
+
[Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
type ReducerMap = Record<string, Reducer>
|
| 43 |
+
|
| 44 |
+
type ExistingSliceLike<DeclaredState, PreloadedState> = {
|
| 45 |
+
[ReducerPath in keyof DeclaredState]: SliceLike<
|
| 46 |
+
ReducerPath & string,
|
| 47 |
+
NonUndefined<DeclaredState[ReducerPath]>,
|
| 48 |
+
NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>
|
| 49 |
+
>
|
| 50 |
+
}[keyof DeclaredState]
|
| 51 |
+
|
| 52 |
+
export type InjectConfig = {
|
| 53 |
+
/**
|
| 54 |
+
* Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
|
| 55 |
+
*/
|
| 56 |
+
overrideExisting?: boolean
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
/**
|
| 60 |
+
* A reducer that allows for slices/reducers to be injected after initialisation.
|
| 61 |
+
*/
|
| 62 |
+
export interface CombinedSliceReducer<
|
| 63 |
+
InitialState,
|
| 64 |
+
DeclaredState extends InitialState = InitialState,
|
| 65 |
+
PreloadedState extends Partial<
|
| 66 |
+
Record<keyof PreloadedState, any>
|
| 67 |
+
> = Partial<DeclaredState>,
|
| 68 |
+
> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
|
| 69 |
+
/**
|
| 70 |
+
* Provide a type for slices that will be injected lazily.
|
| 71 |
+
*
|
| 72 |
+
* One way to do this would be with interface merging:
|
| 73 |
+
* ```ts
|
| 74 |
+
*
|
| 75 |
+
* export interface LazyLoadedSlices {}
|
| 76 |
+
*
|
| 77 |
+
* export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
|
| 78 |
+
*
|
| 79 |
+
* // elsewhere
|
| 80 |
+
*
|
| 81 |
+
* declare module './reducer' {
|
| 82 |
+
* export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
|
| 83 |
+
* }
|
| 84 |
+
*
|
| 85 |
+
* const withBoolean = rootReducer.inject(booleanSlice);
|
| 86 |
+
*
|
| 87 |
+
* // elsewhere again
|
| 88 |
+
*
|
| 89 |
+
* declare module './reducer' {
|
| 90 |
+
* export interface LazyLoadedSlices {
|
| 91 |
+
* customName: CustomState
|
| 92 |
+
* }
|
| 93 |
+
* }
|
| 94 |
+
*
|
| 95 |
+
* const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
|
| 96 |
+
* ```
|
| 97 |
+
*/
|
| 98 |
+
withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<
|
| 99 |
+
InitialState,
|
| 100 |
+
Id<DeclaredState & Partial<Lazy>>,
|
| 101 |
+
Id<PreloadedState & Partial<LazyPreloaded>>
|
| 102 |
+
>
|
| 103 |
+
|
| 104 |
+
/**
|
| 105 |
+
* Inject a slice.
|
| 106 |
+
*
|
| 107 |
+
* Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
|
| 108 |
+
*
|
| 109 |
+
* ```ts
|
| 110 |
+
* rootReducer.inject(booleanSlice)
|
| 111 |
+
* rootReducer.inject(baseApi)
|
| 112 |
+
* rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
|
| 113 |
+
* ```
|
| 114 |
+
*
|
| 115 |
+
*/
|
| 116 |
+
inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(
|
| 117 |
+
slice: Sl,
|
| 118 |
+
config?: InjectConfig,
|
| 119 |
+
): CombinedSliceReducer<
|
| 120 |
+
InitialState,
|
| 121 |
+
Id<DeclaredState & WithSlice<Sl>>,
|
| 122 |
+
Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>
|
| 123 |
+
>
|
| 124 |
+
|
| 125 |
+
/**
|
| 126 |
+
* Inject a slice.
|
| 127 |
+
*
|
| 128 |
+
* Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
|
| 129 |
+
*
|
| 130 |
+
* ```ts
|
| 131 |
+
* rootReducer.inject(booleanSlice)
|
| 132 |
+
* rootReducer.inject(baseApi)
|
| 133 |
+
* rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
|
| 134 |
+
* ```
|
| 135 |
+
*
|
| 136 |
+
*/
|
| 137 |
+
inject<ReducerPath extends string, State, PreloadedState = State>(
|
| 138 |
+
slice: SliceLike<
|
| 139 |
+
ReducerPath,
|
| 140 |
+
State & (ReducerPath extends keyof DeclaredState ? never : State),
|
| 141 |
+
PreloadedState &
|
| 142 |
+
(ReducerPath extends keyof PreloadedState ? never : PreloadedState)
|
| 143 |
+
>,
|
| 144 |
+
config?: InjectConfig,
|
| 145 |
+
): CombinedSliceReducer<
|
| 146 |
+
InitialState,
|
| 147 |
+
Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>,
|
| 148 |
+
Id<
|
| 149 |
+
PreloadedState &
|
| 150 |
+
WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>
|
| 151 |
+
>
|
| 152 |
+
>
|
| 153 |
+
|
| 154 |
+
/**
|
| 155 |
+
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
|
| 156 |
+
*
|
| 157 |
+
* ```ts
|
| 158 |
+
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
|
| 159 |
+
* // ^? boolean | undefined
|
| 160 |
+
*
|
| 161 |
+
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
|
| 162 |
+
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
|
| 163 |
+
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
|
| 164 |
+
* return state.boolean;
|
| 165 |
+
* // ^? boolean
|
| 166 |
+
* })
|
| 167 |
+
* ```
|
| 168 |
+
*
|
| 169 |
+
* If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
|
| 170 |
+
*
|
| 171 |
+
* ```ts
|
| 172 |
+
*
|
| 173 |
+
* export interface LazyLoadedSlices {};
|
| 174 |
+
*
|
| 175 |
+
* export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
|
| 176 |
+
*
|
| 177 |
+
* export const rootReducer = combineSlices({ inner: innerReducer });
|
| 178 |
+
*
|
| 179 |
+
* export type RootState = ReturnType<typeof rootReducer>;
|
| 180 |
+
*
|
| 181 |
+
* // elsewhere
|
| 182 |
+
*
|
| 183 |
+
* declare module "./reducer.ts" {
|
| 184 |
+
* export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
|
| 185 |
+
* }
|
| 186 |
+
*
|
| 187 |
+
* const withBool = innerReducer.inject(booleanSlice);
|
| 188 |
+
*
|
| 189 |
+
* const selectBoolean = withBool.selector(
|
| 190 |
+
* (state) => state.boolean,
|
| 191 |
+
* (rootState: RootState) => state.inner
|
| 192 |
+
* );
|
| 193 |
+
* // now expects to be passed RootState instead of innerReducer state
|
| 194 |
+
*
|
| 195 |
+
* ```
|
| 196 |
+
*
|
| 197 |
+
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
|
| 198 |
+
*
|
| 199 |
+
* ```ts
|
| 200 |
+
* const injectedReducer = rootReducer.inject(booleanSlice);
|
| 201 |
+
* const selectBoolean = injectedReducer.selector((state) => {
|
| 202 |
+
* console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
|
| 203 |
+
* return state.boolean
|
| 204 |
+
* })
|
| 205 |
+
* ```
|
| 206 |
+
*/
|
| 207 |
+
selector: {
|
| 208 |
+
/**
|
| 209 |
+
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
|
| 210 |
+
*
|
| 211 |
+
* ```ts
|
| 212 |
+
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
|
| 213 |
+
* // ^? boolean | undefined
|
| 214 |
+
*
|
| 215 |
+
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
|
| 216 |
+
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
|
| 217 |
+
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
|
| 218 |
+
* return state.boolean;
|
| 219 |
+
* // ^? boolean
|
| 220 |
+
* })
|
| 221 |
+
* ```
|
| 222 |
+
*
|
| 223 |
+
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
|
| 224 |
+
*
|
| 225 |
+
* ```ts
|
| 226 |
+
* const injectedReducer = rootReducer.inject(booleanSlice);
|
| 227 |
+
* const selectBoolean = injectedReducer.selector((state) => {
|
| 228 |
+
* console.log(injectedReducer.selector.original(state).boolean) // undefined
|
| 229 |
+
* return state.boolean
|
| 230 |
+
* })
|
| 231 |
+
* ```
|
| 232 |
+
*/
|
| 233 |
+
<Selector extends (state: DeclaredState, ...args: any[]) => unknown>(
|
| 234 |
+
selectorFn: Selector,
|
| 235 |
+
): (
|
| 236 |
+
state: WithOptionalProp<
|
| 237 |
+
Parameters<Selector>[0],
|
| 238 |
+
Exclude<keyof DeclaredState, keyof InitialState>
|
| 239 |
+
>,
|
| 240 |
+
...args: Tail<Parameters<Selector>>
|
| 241 |
+
) => ReturnType<Selector>
|
| 242 |
+
|
| 243 |
+
/**
|
| 244 |
+
* Create a selector that guarantees that the slices injected will have a defined value when selector is run.
|
| 245 |
+
*
|
| 246 |
+
* ```ts
|
| 247 |
+
* const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
|
| 248 |
+
* // ^? boolean | undefined
|
| 249 |
+
*
|
| 250 |
+
* const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
|
| 251 |
+
* // if action hasn't been dispatched since slice was injected, this would usually be undefined
|
| 252 |
+
* // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
|
| 253 |
+
* return state.boolean;
|
| 254 |
+
* // ^? boolean
|
| 255 |
+
* })
|
| 256 |
+
* ```
|
| 257 |
+
*
|
| 258 |
+
* If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
|
| 259 |
+
*
|
| 260 |
+
* ```ts
|
| 261 |
+
*
|
| 262 |
+
* interface LazyLoadedSlices {};
|
| 263 |
+
*
|
| 264 |
+
* const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
|
| 265 |
+
*
|
| 266 |
+
* const rootReducer = combineSlices({ inner: innerReducer });
|
| 267 |
+
*
|
| 268 |
+
* type RootState = ReturnType<typeof rootReducer>;
|
| 269 |
+
*
|
| 270 |
+
* // elsewhere
|
| 271 |
+
*
|
| 272 |
+
* declare module "./reducer.ts" {
|
| 273 |
+
* interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
|
| 274 |
+
* }
|
| 275 |
+
*
|
| 276 |
+
* const withBool = innerReducer.inject(booleanSlice);
|
| 277 |
+
*
|
| 278 |
+
* const selectBoolean = withBool.selector(
|
| 279 |
+
* (state) => state.boolean,
|
| 280 |
+
* (rootState: RootState) => state.inner
|
| 281 |
+
* );
|
| 282 |
+
* // now expects to be passed RootState instead of innerReducer state
|
| 283 |
+
*
|
| 284 |
+
* ```
|
| 285 |
+
*
|
| 286 |
+
* Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
|
| 287 |
+
*
|
| 288 |
+
* ```ts
|
| 289 |
+
* const injectedReducer = rootReducer.inject(booleanSlice);
|
| 290 |
+
* const selectBoolean = injectedReducer.selector((state) => {
|
| 291 |
+
* console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
|
| 292 |
+
* return state.boolean
|
| 293 |
+
* })
|
| 294 |
+
* ```
|
| 295 |
+
*/
|
| 296 |
+
<
|
| 297 |
+
Selector extends (state: DeclaredState, ...args: any[]) => unknown,
|
| 298 |
+
RootState,
|
| 299 |
+
>(
|
| 300 |
+
selectorFn: Selector,
|
| 301 |
+
selectState: (
|
| 302 |
+
rootState: RootState,
|
| 303 |
+
...args: Tail<Parameters<Selector>>
|
| 304 |
+
) => WithOptionalProp<
|
| 305 |
+
Parameters<Selector>[0],
|
| 306 |
+
Exclude<keyof DeclaredState, keyof InitialState>
|
| 307 |
+
>,
|
| 308 |
+
): (
|
| 309 |
+
state: RootState,
|
| 310 |
+
...args: Tail<Parameters<Selector>>
|
| 311 |
+
) => ReturnType<Selector>
|
| 312 |
+
/**
|
| 313 |
+
* Returns the unproxied state. Useful for debugging.
|
| 314 |
+
* @param state state Proxy, that ensures injected reducers have value
|
| 315 |
+
* @returns original, unproxied state
|
| 316 |
+
* @throws if value passed is not a state Proxy
|
| 317 |
+
*/
|
| 318 |
+
original: (state: DeclaredState) => InitialState & Partial<DeclaredState>
|
| 319 |
+
}
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> =
|
| 323 |
+
UnionToIntersection<
|
| 324 |
+
Slices[number] extends infer Slice
|
| 325 |
+
? Slice extends AnySliceLike
|
| 326 |
+
? WithSlice<Slice>
|
| 327 |
+
: StateFromReducersMapObject<Slice>
|
| 328 |
+
: never
|
| 329 |
+
>
|
| 330 |
+
|
| 331 |
+
type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> =
|
| 332 |
+
UnionToIntersection<
|
| 333 |
+
Slices[number] extends infer Slice
|
| 334 |
+
? Slice extends AnySliceLike
|
| 335 |
+
? WithSlicePreloadedState<Slice>
|
| 336 |
+
: PreloadedStateShapeFromReducersMapObject<Slice>
|
| 337 |
+
: never
|
| 338 |
+
>
|
| 339 |
+
|
| 340 |
+
const isSliceLike = (
|
| 341 |
+
maybeSliceLike: AnySliceLike | ReducerMap,
|
| 342 |
+
): maybeSliceLike is AnySliceLike =>
|
| 343 |
+
'reducerPath' in maybeSliceLike &&
|
| 344 |
+
typeof maybeSliceLike.reducerPath === 'string'
|
| 345 |
+
|
| 346 |
+
const getReducers = (slices: Array<AnySliceLike | ReducerMap>) =>
|
| 347 |
+
slices.flatMap<[string, Reducer]>((sliceOrMap) =>
|
| 348 |
+
isSliceLike(sliceOrMap)
|
| 349 |
+
? [[sliceOrMap.reducerPath, sliceOrMap.reducer]]
|
| 350 |
+
: Object.entries(sliceOrMap),
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
const ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original')
|
| 354 |
+
|
| 355 |
+
const isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE]
|
| 356 |
+
|
| 357 |
+
const stateProxyMap = new WeakMap<object, object>()
|
| 358 |
+
|
| 359 |
+
const createStateProxy = <State extends object>(
|
| 360 |
+
state: State,
|
| 361 |
+
reducerMap: Partial<Record<PropertyKey, Reducer>>,
|
| 362 |
+
initialStateCache: Record<PropertyKey, unknown>,
|
| 363 |
+
) =>
|
| 364 |
+
getOrInsertComputed(
|
| 365 |
+
stateProxyMap,
|
| 366 |
+
state,
|
| 367 |
+
() =>
|
| 368 |
+
new Proxy(state, {
|
| 369 |
+
get: (target, prop, receiver) => {
|
| 370 |
+
if (prop === ORIGINAL_STATE) return target
|
| 371 |
+
const result = Reflect.get(target, prop, receiver)
|
| 372 |
+
if (typeof result === 'undefined') {
|
| 373 |
+
const cached = initialStateCache[prop]
|
| 374 |
+
if (typeof cached !== 'undefined') return cached
|
| 375 |
+
const reducer = reducerMap[prop]
|
| 376 |
+
if (reducer) {
|
| 377 |
+
// ensure action type is random, to prevent reducer treating it differently
|
| 378 |
+
const reducerResult = reducer(undefined, { type: nanoid() })
|
| 379 |
+
if (typeof reducerResult === 'undefined') {
|
| 380 |
+
throw new Error(
|
| 381 |
+
`The slice reducer for key "${prop.toString()}" returned undefined when called for selector(). ` +
|
| 382 |
+
`If the state passed to the reducer is undefined, you must ` +
|
| 383 |
+
`explicitly return the initial state. The initial state may ` +
|
| 384 |
+
`not be undefined. If you don't want to set a value for this reducer, ` +
|
| 385 |
+
`you can use null instead of undefined.`,
|
| 386 |
+
)
|
| 387 |
+
}
|
| 388 |
+
initialStateCache[prop] = reducerResult
|
| 389 |
+
return reducerResult
|
| 390 |
+
}
|
| 391 |
+
}
|
| 392 |
+
return result
|
| 393 |
+
},
|
| 394 |
+
}),
|
| 395 |
+
) as State
|
| 396 |
+
|
| 397 |
+
const original = (state: any) => {
|
| 398 |
+
if (!isStateProxy(state)) {
|
| 399 |
+
throw new Error('original must be used on state Proxy')
|
| 400 |
+
}
|
| 401 |
+
return state[ORIGINAL_STATE]
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
const emptyObject = {}
|
| 405 |
+
const noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state
|
| 406 |
+
|
| 407 |
+
export function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(
|
| 408 |
+
...slices: Slices
|
| 409 |
+
): CombinedSliceReducer<
|
| 410 |
+
Id<InitialState<Slices>>,
|
| 411 |
+
Id<InitialState<Slices>>,
|
| 412 |
+
Partial<Id<InitialPreloadedState<Slices>>>
|
| 413 |
+
> {
|
| 414 |
+
const reducerMap = Object.fromEntries(getReducers(slices))
|
| 415 |
+
|
| 416 |
+
const getReducer = () =>
|
| 417 |
+
Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer
|
| 418 |
+
|
| 419 |
+
let reducer = getReducer()
|
| 420 |
+
|
| 421 |
+
function combinedReducer(
|
| 422 |
+
state: Record<string, unknown>,
|
| 423 |
+
action: UnknownAction,
|
| 424 |
+
) {
|
| 425 |
+
return reducer(state, action)
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
combinedReducer.withLazyLoadedSlices = () => combinedReducer
|
| 429 |
+
|
| 430 |
+
const initialStateCache: Record<PropertyKey, unknown> = {}
|
| 431 |
+
|
| 432 |
+
const inject = (
|
| 433 |
+
slice: AnySliceLike,
|
| 434 |
+
config: InjectConfig = {},
|
| 435 |
+
): typeof combinedReducer => {
|
| 436 |
+
const { reducerPath, reducer: reducerToInject } = slice
|
| 437 |
+
|
| 438 |
+
const currentReducer = reducerMap[reducerPath]
|
| 439 |
+
if (
|
| 440 |
+
!config.overrideExisting &&
|
| 441 |
+
currentReducer &&
|
| 442 |
+
currentReducer !== reducerToInject
|
| 443 |
+
) {
|
| 444 |
+
if (
|
| 445 |
+
typeof process !== 'undefined' &&
|
| 446 |
+
process.env.NODE_ENV === 'development'
|
| 447 |
+
) {
|
| 448 |
+
console.error(
|
| 449 |
+
`called \`inject\` to override already-existing reducer ${reducerPath} without specifying \`overrideExisting: true\``,
|
| 450 |
+
)
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
return combinedReducer
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
if (config.overrideExisting && currentReducer !== reducerToInject) {
|
| 457 |
+
delete initialStateCache[reducerPath]
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
reducerMap[reducerPath] = reducerToInject
|
| 461 |
+
|
| 462 |
+
reducer = getReducer()
|
| 463 |
+
|
| 464 |
+
return combinedReducer
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
const selector = Object.assign(
|
| 468 |
+
function makeSelector<State extends object, RootState, Args extends any[]>(
|
| 469 |
+
selectorFn: (state: State, ...args: Args) => any,
|
| 470 |
+
selectState?: (rootState: RootState, ...args: Args) => State,
|
| 471 |
+
) {
|
| 472 |
+
return function selector(state: State, ...args: Args) {
|
| 473 |
+
return selectorFn(
|
| 474 |
+
createStateProxy(
|
| 475 |
+
selectState ? selectState(state as any, ...args) : state,
|
| 476 |
+
reducerMap,
|
| 477 |
+
initialStateCache,
|
| 478 |
+
),
|
| 479 |
+
...args,
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {
|
| 2 |
+
Reducer,
|
| 3 |
+
ReducersMapObject,
|
| 4 |
+
Middleware,
|
| 5 |
+
Action,
|
| 6 |
+
StoreEnhancer,
|
| 7 |
+
Store,
|
| 8 |
+
UnknownAction,
|
| 9 |
+
} from 'redux'
|
| 10 |
+
import {
|
| 11 |
+
applyMiddleware,
|
| 12 |
+
createStore,
|
| 13 |
+
compose,
|
| 14 |
+
combineReducers,
|
| 15 |
+
isPlainObject,
|
| 16 |
+
} from './reduxImports'
|
| 17 |
+
import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'
|
| 18 |
+
import { composeWithDevTools } from './devtoolsExtension'
|
| 19 |
+
|
| 20 |
+
import type {
|
| 21 |
+
ThunkMiddlewareFor,
|
| 22 |
+
GetDefaultMiddleware,
|
| 23 |
+
} from './getDefaultMiddleware'
|
| 24 |
+
import { buildGetDefaultMiddleware } from './getDefaultMiddleware'
|
| 25 |
+
import type {
|
| 26 |
+
ExtractDispatchExtensions,
|
| 27 |
+
ExtractStoreExtensions,
|
| 28 |
+
ExtractStateExtensions,
|
| 29 |
+
UnknownIfNonSpecific,
|
| 30 |
+
} from './tsHelpers'
|
| 31 |
+
import type { Tuple } from './utils'
|
| 32 |
+
import type { GetDefaultEnhancers } from './getDefaultEnhancers'
|
| 33 |
+
import { buildGetDefaultEnhancers } from './getDefaultEnhancers'
|
| 34 |
+
|
| 35 |
+
/**
|
| 36 |
+
* Options for `configureStore()`.
|
| 37 |
+
*
|
| 38 |
+
* @public
|
| 39 |
+
*/
|
| 40 |
+
export interface ConfigureStoreOptions<
|
| 41 |
+
S = any,
|
| 42 |
+
A extends Action = UnknownAction,
|
| 43 |
+
M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,
|
| 44 |
+
E extends Tuple<Enhancers> = Tuple<Enhancers>,
|
| 45 |
+
P = S,
|
| 46 |
+
> {
|
| 47 |
+
/**
|
| 48 |
+
* A single reducer function that will be used as the root reducer, or an
|
| 49 |
+
* object of slice reducers that will be passed to `combineReducers()`.
|
| 50 |
+
*/
|
| 51 |
+
reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>
|
| 52 |
+
|
| 53 |
+
/**
|
| 54 |
+
* An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
|
| 55 |
+
* If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
|
| 56 |
+
*
|
| 57 |
+
* @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
|
| 58 |
+
* @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
|
| 59 |
+
*/
|
| 60 |
+
middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M
|
| 61 |
+
|
| 62 |
+
/**
|
| 63 |
+
* Whether to enable Redux DevTools integration. Defaults to `true`.
|
| 64 |
+
*
|
| 65 |
+
* Additional configuration can be done by passing Redux DevTools options
|
| 66 |
+
*/
|
| 67 |
+
devTools?: boolean | DevToolsOptions
|
| 68 |
+
|
| 69 |
+
/**
|
| 70 |
+
* Whether to check for duplicate middleware instances. Defaults to `true`.
|
| 71 |
+
*/
|
| 72 |
+
duplicateMiddlewareCheck?: boolean
|
| 73 |
+
|
| 74 |
+
/**
|
| 75 |
+
* The initial state, same as Redux's createStore.
|
| 76 |
+
* You may optionally specify it to hydrate the state
|
| 77 |
+
* from the server in universal apps, or to restore a previously serialized
|
| 78 |
+
* user session. If you use `combineReducers()` to produce the root reducer
|
| 79 |
+
* function (either directly or indirectly by passing an object as `reducer`),
|
| 80 |
+
* this must be an object with the same shape as the reducer map keys.
|
| 81 |
+
*/
|
| 82 |
+
// we infer here, and instead complain if the reducer doesn't match
|
| 83 |
+
preloadedState?: P
|
| 84 |
+
|
| 85 |
+
/**
|
| 86 |
+
* The store enhancers to apply. See Redux's `createStore()`.
|
| 87 |
+
* All enhancers will be included before the DevTools Extension enhancer.
|
| 88 |
+
* If you need to customize the order of enhancers, supply a callback
|
| 89 |
+
* function that will receive a `getDefaultEnhancers` function that returns a Tuple,
|
| 90 |
+
* and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
|
| 91 |
+
* If you only need to add middleware, you can use the `middleware` parameter instead.
|
| 92 |
+
*/
|
| 93 |
+
enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
export type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>
|
| 97 |
+
|
| 98 |
+
type Enhancers = ReadonlyArray<StoreEnhancer>
|
| 99 |
+
|
| 100 |
+
/**
|
| 101 |
+
* A Redux store returned by `configureStore()`. Supports dispatching
|
| 102 |
+
* side-effectful _thunks_ in addition to plain actions.
|
| 103 |
+
*
|
| 104 |
+
* @public
|
| 105 |
+
*/
|
| 106 |
+
export type EnhancedStore<
|
| 107 |
+
S = any,
|
| 108 |
+
A extends Action = UnknownAction,
|
| 109 |
+
E extends Enhancers = Enhancers,
|
| 110 |
+
> = ExtractStoreExtensions<E> &
|
| 111 |
+
Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>
|
| 112 |
+
|
| 113 |
+
/**
|
| 114 |
+
* A friendly abstraction over the standard Redux `createStore()` function.
|
| 115 |
+
*
|
| 116 |
+
* @param options The store configuration.
|
| 117 |
+
* @returns A configured Redux store.
|
| 118 |
+
*
|
| 119 |
+
* @public
|
| 120 |
+
*/
|
| 121 |
+
export function configureStore<
|
| 122 |
+
S = any,
|
| 123 |
+
A extends Action = UnknownAction,
|
| 124 |
+
M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,
|
| 125 |
+
E extends Tuple<Enhancers> = Tuple<
|
| 126 |
+
[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]
|
| 127 |
+
>,
|
| 128 |
+
P = S,
|
| 129 |
+
>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {
|
| 130 |
+
const getDefaultMiddleware = buildGetDefaultMiddleware<S>()
|
| 131 |
+
|
| 132 |
+
const {
|
| 133 |
+
reducer = undefined,
|
| 134 |
+
middleware,
|
| 135 |
+
devTools = true,
|
| 136 |
+
duplicateMiddlewareCheck = true,
|
| 137 |
+
preloadedState = undefined,
|
| 138 |
+
enhancers = undefined,
|
| 139 |
+
} = options || {}
|
| 140 |
+
|
| 141 |
+
let rootReducer: Reducer<S, A, P>
|
| 142 |
+
|
| 143 |
+
if (typeof reducer === 'function') {
|
| 144 |
+
rootReducer = reducer
|
| 145 |
+
} else if (isPlainObject(reducer)) {
|
| 146 |
+
rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>
|
| 147 |
+
} else {
|
| 148 |
+
throw new Error(
|
| 149 |
+
'`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',
|
| 150 |
+
)
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
if (
|
| 154 |
+
process.env.NODE_ENV !== 'production' &&
|
| 155 |
+
middleware &&
|
| 156 |
+
typeof middleware !== 'function'
|
| 157 |
+
) {
|
| 158 |
+
throw new Error('`middleware` field must be a callback')
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
let finalMiddleware: Tuple<Middlewares<S>>
|
| 162 |
+
if (typeof middleware === 'function') {
|
| 163 |
+
finalMiddleware = middleware(getDefaultMiddleware)
|
| 164 |
+
|
| 165 |
+
if (
|
| 166 |
+
process.env.NODE_ENV !== 'production' &&
|
| 167 |
+
!Array.isArray(finalMiddleware)
|
| 168 |
+
) {
|
| 169 |
+
throw new Error(
|
| 170 |
+
'when using a middleware builder function, an array of middleware must be returned',
|
| 171 |
+
)
|
| 172 |
+
}
|
| 173 |
+
} else {
|
| 174 |
+
finalMiddleware = getDefaultMiddleware()
|
| 175 |
+
}
|
| 176 |
+
if (
|
| 177 |
+
process.env.NODE_ENV !== 'production' &&
|
| 178 |
+
finalMiddleware.some((item: any) => typeof item !== 'function')
|
| 179 |
+
) {
|
| 180 |
+
throw new Error(
|
| 181 |
+
'each middleware provided to configureStore must be a function',
|
| 182 |
+
)
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {
|
| 186 |
+
let middlewareReferences = new Set<Middleware<any, S>>()
|
| 187 |
+
finalMiddleware.forEach((middleware) => {
|
| 188 |
+
if (middlewareReferences.has(middleware)) {
|
| 189 |
+
throw new Error(
|
| 190 |
+
'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
|
| 191 |
+
)
|
| 192 |
+
}
|
| 193 |
+
middlewareReferences.add(middleware)
|
| 194 |
+
})
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
let finalCompose = compose
|
| 198 |
+
|
| 199 |
+
if (devTools) {
|
| 200 |
+
finalCompose = composeWithDevTools({
|
| 201 |
+
// Enable capture of stack traces for dispatched Redux actions
|
| 202 |
+
trace: process.env.NODE_ENV !== 'production',
|
| 203 |
+
...(typeof devTools === 'object' && devTools),
|
| 204 |
+
})
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
const middlewareEnhancer = applyMiddleware(...finalMiddleware)
|
| 208 |
+
|
| 209 |
+
const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)
|
| 210 |
+
|
| 211 |
+
if (
|
| 212 |
+
process.env.NODE_ENV !== 'production' &&
|
| 213 |
+
enhancers &&
|
| 214 |
+
typeof enhancers !== 'function'
|
| 215 |
+
) {
|
| 216 |
+
throw new Error('`enhancers` field must be a callback')
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
let storeEnhancers =
|
| 220 |
+
typeof enhancers === 'function'
|
| 221 |
+
? enhancers(getDefaultEnhancers)
|
| 222 |
+
: getDefaultEnhancers()
|
| 223 |
+
|
| 224 |
+
if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {
|
| 225 |
+
throw new Error('`enhancers` callback must return an array')
|
| 226 |
+
}
|
| 227 |
+
if (
|
| 228 |
+
process.env.NODE_ENV !== 'production' &&
|
| 229 |
+
storeEnhancers.some((item: any) => typeof item !== 'function')
|
| 230 |
+
) {
|
| 231 |
+
throw new Error(
|
| 232 |
+
'each enhancer provided to configureStore must be a function',
|
| 233 |
+
)
|
| 234 |
+
}
|
| 235 |
+
if (
|
| 236 |
+
process.env.NODE_ENV !== 'production' &&
|
| 237 |
+
finalMiddleware.length &&
|
| 238 |
+
!storeEnhancers.includes(middlewareEnhancer)
|
| 239 |
+
) {
|
| 240 |
+
console.error(
|
| 241 |
+
'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',
|
| 242 |
+
)
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
const composedEnhancer: StoreEnhancer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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { isAction } from './reduxImports'
|
| 2 |
+
import type {
|
| 3 |
+
IsUnknownOrNonInferrable,
|
| 4 |
+
IfMaybeUndefined,
|
| 5 |
+
IfVoid,
|
| 6 |
+
IsAny,
|
| 7 |
+
} from './tsHelpers'
|
| 8 |
+
import { hasMatchFunction } from './tsHelpers'
|
| 9 |
+
|
| 10 |
+
/**
|
| 11 |
+
* An action with a string type and an associated payload. This is the
|
| 12 |
+
* type of action returned by `createAction()` action creators.
|
| 13 |
+
*
|
| 14 |
+
* @template P The type of the action's payload.
|
| 15 |
+
* @template T the type used for the action type.
|
| 16 |
+
* @template M The type of the action's meta (optional)
|
| 17 |
+
* @template E The type of the action's error (optional)
|
| 18 |
+
*
|
| 19 |
+
* @public
|
| 20 |
+
*/
|
| 21 |
+
export type PayloadAction<
|
| 22 |
+
P = void,
|
| 23 |
+
T extends string = string,
|
| 24 |
+
M = never,
|
| 25 |
+
E = never,
|
| 26 |
+
> = {
|
| 27 |
+
payload: P
|
| 28 |
+
type: T
|
| 29 |
+
} & ([M] extends [never]
|
| 30 |
+
? {}
|
| 31 |
+
: {
|
| 32 |
+
meta: M
|
| 33 |
+
}) &
|
| 34 |
+
([E] extends [never]
|
| 35 |
+
? {}
|
| 36 |
+
: {
|
| 37 |
+
error: E
|
| 38 |
+
})
|
| 39 |
+
|
| 40 |
+
/**
|
| 41 |
+
* A "prepare" method to be used as the second parameter of `createAction`.
|
| 42 |
+
* Takes any number of arguments and returns a Flux Standard Action without
|
| 43 |
+
* type (will be added later) that *must* contain a payload (might be undefined).
|
| 44 |
+
*
|
| 45 |
+
* @public
|
| 46 |
+
*/
|
| 47 |
+
export type PrepareAction<P> =
|
| 48 |
+
| ((...args: any[]) => { payload: P })
|
| 49 |
+
| ((...args: any[]) => { payload: P; meta: any })
|
| 50 |
+
| ((...args: any[]) => { payload: P; error: any })
|
| 51 |
+
| ((...args: any[]) => { payload: P; meta: any; error: any })
|
| 52 |
+
|
| 53 |
+
/**
|
| 54 |
+
* Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
|
| 55 |
+
*
|
| 56 |
+
* @internal
|
| 57 |
+
*/
|
| 58 |
+
export type _ActionCreatorWithPreparedPayload<
|
| 59 |
+
PA extends PrepareAction<any> | void,
|
| 60 |
+
T extends string = string,
|
| 61 |
+
> =
|
| 62 |
+
PA extends PrepareAction<infer P>
|
| 63 |
+
? ActionCreatorWithPreparedPayload<
|
| 64 |
+
Parameters<PA>,
|
| 65 |
+
P,
|
| 66 |
+
T,
|
| 67 |
+
ReturnType<PA> extends {
|
| 68 |
+
error: infer E
|
| 69 |
+
}
|
| 70 |
+
? E
|
| 71 |
+
: never,
|
| 72 |
+
ReturnType<PA> extends {
|
| 73 |
+
meta: infer M
|
| 74 |
+
}
|
| 75 |
+
? M
|
| 76 |
+
: never
|
| 77 |
+
>
|
| 78 |
+
: void
|
| 79 |
+
|
| 80 |
+
/**
|
| 81 |
+
* Basic type for all action creators.
|
| 82 |
+
*
|
| 83 |
+
* @inheritdoc {redux#ActionCreator}
|
| 84 |
+
*/
|
| 85 |
+
export type BaseActionCreator<P, T extends string, M = never, E = never> = {
|
| 86 |
+
type: T
|
| 87 |
+
match: (action: unknown) => action is PayloadAction<P, T, M, E>
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
/**
|
| 91 |
+
* An action creator that takes multiple arguments that are passed
|
| 92 |
+
* to a `PrepareAction` method to create the final Action.
|
| 93 |
+
* @typeParam Args arguments for the action creator function
|
| 94 |
+
* @typeParam P `payload` type
|
| 95 |
+
* @typeParam T `type` name
|
| 96 |
+
* @typeParam E optional `error` type
|
| 97 |
+
* @typeParam M optional `meta` type
|
| 98 |
+
*
|
| 99 |
+
* @inheritdoc {redux#ActionCreator}
|
| 100 |
+
*
|
| 101 |
+
* @public
|
| 102 |
+
*/
|
| 103 |
+
export interface ActionCreatorWithPreparedPayload<
|
| 104 |
+
Args extends unknown[],
|
| 105 |
+
P,
|
| 106 |
+
T extends string = string,
|
| 107 |
+
E = never,
|
| 108 |
+
M = never,
|
| 109 |
+
> extends BaseActionCreator<P, T, M, E> {
|
| 110 |
+
/**
|
| 111 |
+
* Calling this {@link redux#ActionCreator} with `Args` will return
|
| 112 |
+
* an Action with a payload of type `P` and (depending on the `PrepareAction`
|
| 113 |
+
* method used) a `meta`- and `error` property of types `M` and `E` respectively.
|
| 114 |
+
*/
|
| 115 |
+
(...args: Args): PayloadAction<P, T, M, E>
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/**
|
| 119 |
+
* An action creator of type `T` that takes an optional payload of type `P`.
|
| 120 |
+
*
|
| 121 |
+
* @inheritdoc {redux#ActionCreator}
|
| 122 |
+
*
|
| 123 |
+
* @public
|
| 124 |
+
*/
|
| 125 |
+
export interface ActionCreatorWithOptionalPayload<P, T extends string = string>
|
| 126 |
+
extends BaseActionCreator<P, T> {
|
| 127 |
+
/**
|
| 128 |
+
* Calling this {@link redux#ActionCreator} with an argument will
|
| 129 |
+
* return a {@link PayloadAction} of type `T` with a payload of `P`.
|
| 130 |
+
* Calling it without an argument will return a PayloadAction with a payload of `undefined`.
|
| 131 |
+
*/
|
| 132 |
+
(payload?: P): PayloadAction<P, T>
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
/**
|
| 136 |
+
* An action creator of type `T` that takes no payload.
|
| 137 |
+
*
|
| 138 |
+
* @inheritdoc {redux#ActionCreator}
|
| 139 |
+
*
|
| 140 |
+
* @public
|
| 141 |
+
*/
|
| 142 |
+
export interface ActionCreatorWithoutPayload<T extends string = string>
|
| 143 |
+
extends BaseActionCreator<undefined, T> {
|
| 144 |
+
/**
|
| 145 |
+
* Calling this {@link redux#ActionCreator} will
|
| 146 |
+
* return a {@link PayloadAction} of type `T` with a payload of `undefined`
|
| 147 |
+
*/
|
| 148 |
+
(noArgument: void): PayloadAction<undefined, T>
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
/**
|
| 152 |
+
* An action creator of type `T` that requires a payload of type P.
|
| 153 |
+
*
|
| 154 |
+
* @inheritdoc {redux#ActionCreator}
|
| 155 |
+
*
|
| 156 |
+
* @public
|
| 157 |
+
*/
|
| 158 |
+
export interface ActionCreatorWithPayload<P, T extends string = string>
|
| 159 |
+
extends BaseActionCreator<P, T> {
|
| 160 |
+
/**
|
| 161 |
+
* Calling this {@link redux#ActionCreator} with an argument will
|
| 162 |
+
* return a {@link PayloadAction} of type `T` with a payload of `P`
|
| 163 |
+
*/
|
| 164 |
+
(payload: P): PayloadAction<P, T>
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/**
|
| 168 |
+
* An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
|
| 169 |
+
*
|
| 170 |
+
* @inheritdoc {redux#ActionCreator}
|
| 171 |
+
*
|
| 172 |
+
* @public
|
| 173 |
+
*/
|
| 174 |
+
export interface ActionCreatorWithNonInferrablePayload<
|
| 175 |
+
T extends string = string,
|
| 176 |
+
> extends BaseActionCreator<unknown, T> {
|
| 177 |
+
/**
|
| 178 |
+
* Calling this {@link redux#ActionCreator} with an argument will
|
| 179 |
+
* return a {@link PayloadAction} of type `T` with a payload
|
| 180 |
+
* of exactly the type of the argument.
|
| 181 |
+
*/
|
| 182 |
+
<PT extends unknown>(payload: PT): PayloadAction<PT, T>
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
/**
|
| 186 |
+
* An action creator that produces actions with a `payload` attribute.
|
| 187 |
+
*
|
| 188 |
+
* @typeParam P the `payload` type
|
| 189 |
+
* @typeParam T the `type` of the resulting action
|
| 190 |
+
* @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
|
| 191 |
+
*
|
| 192 |
+
* @public
|
| 193 |
+
*/
|
| 194 |
+
export type PayloadActionCreator<
|
| 195 |
+
P = void,
|
| 196 |
+
T extends string = string,
|
| 197 |
+
PA extends PrepareAction<P> | void = void,
|
| 198 |
+
> = IfPrepareActionMethodProvided<
|
| 199 |
+
PA,
|
| 200 |
+
_ActionCreatorWithPreparedPayload<PA, T>,
|
| 201 |
+
// else
|
| 202 |
+
IsAny<
|
| 203 |
+
P,
|
| 204 |
+
ActionCreatorWithPayload<any, T>,
|
| 205 |
+
IsUnknownOrNonInferrable<
|
| 206 |
+
P,
|
| 207 |
+
ActionCreatorWithNonInferrablePayload<T>,
|
| 208 |
+
// else
|
| 209 |
+
IfVoid<
|
| 210 |
+
P,
|
| 211 |
+
ActionCreatorWithoutPayload<T>,
|
| 212 |
+
// else
|
| 213 |
+
IfMaybeUndefined<
|
| 214 |
+
P,
|
| 215 |
+
ActionCreatorWithOptionalPayload<P, T>,
|
| 216 |
+
// else
|
| 217 |
+
ActionCreatorWithPayload<P, T>
|
| 218 |
+
>
|
| 219 |
+
>
|
| 220 |
+
>
|
| 221 |
+
>
|
| 222 |
+
>
|
| 223 |
+
|
| 224 |
+
/**
|
| 225 |
+
* A utility function to create an action creator for the given action type
|
| 226 |
+
* string. The action creator accepts a single argument, which will be included
|
| 227 |
+
* in the action object as a field called payload. The action creator function
|
| 228 |
+
* will also have its toString() overridden so that it returns the action type.
|
| 229 |
+
*
|
| 230 |
+
* @param type The action type to use for created actions.
|
| 231 |
+
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
|
| 232 |
+
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
|
| 233 |
+
*
|
| 234 |
+
* @public
|
| 235 |
+
*/
|
| 236 |
+
export function createAction<P = void, T extends string = string>(
|
| 237 |
+
type: T,
|
| 238 |
+
): PayloadActionCreator<P, T>
|
| 239 |
+
|
| 240 |
+
/**
|
| 241 |
+
* A utility function to create an action creator for the given action type
|
| 242 |
+
* string. The action creator accepts a single argument, which will be included
|
| 243 |
+
* in the action object as a field called payload. The action creator function
|
| 244 |
+
* will also have its toString() overridden so that it returns the action type.
|
| 245 |
+
*
|
| 246 |
+
* @param type The action type to use for created actions.
|
| 247 |
+
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
|
| 248 |
+
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
|
| 249 |
+
*
|
| 250 |
+
* @public
|
| 251 |
+
*/
|
| 252 |
+
export function createAction<
|
| 253 |
+
PA extends PrepareAction<any>,
|
| 254 |
+
T extends string = string,
|
| 255 |
+
>(
|
| 256 |
+
type: T,
|
| 257 |
+
prepareAction: PA,
|
| 258 |
+
): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
|
| 259 |
+
|
| 260 |
+
export function createAction(type: string, prepareAction?: Function): any {
|
| 261 |
+
function actionCreator(...args: any[]) {
|
| 262 |
+
if (prepareAction) {
|
| 263 |
+
let prepared = prepareAction(...args)
|
| 264 |
+
if (!prepared) {
|
| 265 |
+
throw new Error('prepareAction did not return an object')
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
return {
|
| 269 |
+
type,
|
| 270 |
+
payload: prepared.payload,
|
| 271 |
+
...('meta' in prepared && { meta: prepared.meta }),
|
| 272 |
+
...('error' in prepared && { error: prepared.error }),
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
return { type, payload: args[0] }
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
actionCreator.toString = () => `${type}`
|
| 279 |
+
|
| 280 |
+
actionCreator.type = type
|
| 281 |
+
|
| 282 |
+
actionCreator.match = (action: unknown): action is PayloadAction =>
|
| 283 |
+
isAction(action) && action.type === type
|
| 284 |
+
|
| 285 |
+
return actionCreator
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/**
|
| 289 |
+
* Returns true if value is an RTK-like action creator, with a static type property and match method.
|
| 290 |
+
*/
|
| 291 |
+
export function isActionCreator(
|
| 292 |
+
action: unknown,
|
| 293 |
+
): action is BaseActionCreator<unknown, string> & Function {
|
| 294 |
+
return (
|
| 295 |
+
typeof action === 'function' &&
|
| 296 |
+
'type' in action &&
|
| 297 |
+
// hasMatchFunction only wants Matchers but I don't see the point in rewriting it
|
| 298 |
+
hasMatchFunction(action as any)
|
| 299 |
+
)
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/**
|
| 303 |
+
* Returns true if value is an action with a string type and valid Flux Standard Action keys.
|
| 304 |
+
*/
|
| 305 |
+
export function isFSA(action: unknown): action is {
|
| 306 |
+
type: string
|
| 307 |
+
payload?: unknown
|
| 308 |
+
error?: unknown
|
| 309 |
+
meta?: unknown
|
| 310 |
+
} {
|
| 311 |
+
return isAction(action) && Object.keys(action).every(isValidKey)
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
function isValidKey(key: string) {
|
| 315 |
+
return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
// helper types for more readable typings
|
| 319 |
+
|
| 320 |
+
type IfPrepareActionMethodProvided<
|
| 321 |
+
PA extends PrepareAction<any> | void,
|
| 322 |
+
True,
|
| 323 |
+
False,
|
| 324 |
+
> = PA extends (...args: any[]) => any ? True : False
|
node_modules/@reduxjs/toolkit/src/createAsyncThunk.ts
ADDED
|
@@ -0,0 +1,791 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Dispatch, UnknownAction } from 'redux'
|
| 2 |
+
import type { ThunkDispatch } from 'redux-thunk'
|
| 3 |
+
import type { ActionCreatorWithPreparedPayload } from './createAction'
|
| 4 |
+
import { createAction } from './createAction'
|
| 5 |
+
import { isAnyOf } from './matchers'
|
| 6 |
+
import { nanoid } from './nanoid'
|
| 7 |
+
import type {
|
| 8 |
+
FallbackIfUnknown,
|
| 9 |
+
Id,
|
| 10 |
+
IsAny,
|
| 11 |
+
IsUnknown,
|
| 12 |
+
SafePromise,
|
| 13 |
+
} from './tsHelpers'
|
| 14 |
+
|
| 15 |
+
export type BaseThunkAPI<
|
| 16 |
+
S,
|
| 17 |
+
E,
|
| 18 |
+
D extends Dispatch = Dispatch,
|
| 19 |
+
RejectedValue = unknown,
|
| 20 |
+
RejectedMeta = unknown,
|
| 21 |
+
FulfilledMeta = unknown,
|
| 22 |
+
> = {
|
| 23 |
+
dispatch: D
|
| 24 |
+
getState: () => S
|
| 25 |
+
extra: E
|
| 26 |
+
requestId: string
|
| 27 |
+
signal: AbortSignal
|
| 28 |
+
abort: (reason?: string) => void
|
| 29 |
+
rejectWithValue: IsUnknown<
|
| 30 |
+
RejectedMeta,
|
| 31 |
+
(value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,
|
| 32 |
+
(
|
| 33 |
+
value: RejectedValue,
|
| 34 |
+
meta: RejectedMeta,
|
| 35 |
+
) => RejectWithValue<RejectedValue, RejectedMeta>
|
| 36 |
+
>
|
| 37 |
+
fulfillWithValue: IsUnknown<
|
| 38 |
+
FulfilledMeta,
|
| 39 |
+
<FulfilledValue>(value: FulfilledValue) => FulfilledValue,
|
| 40 |
+
<FulfilledValue>(
|
| 41 |
+
value: FulfilledValue,
|
| 42 |
+
meta: FulfilledMeta,
|
| 43 |
+
) => FulfillWithMeta<FulfilledValue, FulfilledMeta>
|
| 44 |
+
>
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/**
|
| 48 |
+
* @public
|
| 49 |
+
*/
|
| 50 |
+
export interface SerializedError {
|
| 51 |
+
name?: string
|
| 52 |
+
message?: string
|
| 53 |
+
stack?: string
|
| 54 |
+
code?: string
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
const commonProperties: Array<keyof SerializedError> = [
|
| 58 |
+
'name',
|
| 59 |
+
'message',
|
| 60 |
+
'stack',
|
| 61 |
+
'code',
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
class RejectWithValue<Payload, RejectedMeta> {
|
| 65 |
+
/*
|
| 66 |
+
type-only property to distinguish between RejectWithValue and FulfillWithMeta
|
| 67 |
+
does not exist at runtime
|
| 68 |
+
*/
|
| 69 |
+
private readonly _type!: 'RejectWithValue'
|
| 70 |
+
constructor(
|
| 71 |
+
public readonly payload: Payload,
|
| 72 |
+
public readonly meta: RejectedMeta,
|
| 73 |
+
) {}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
class FulfillWithMeta<Payload, FulfilledMeta> {
|
| 77 |
+
/*
|
| 78 |
+
type-only property to distinguish between RejectWithValue and FulfillWithMeta
|
| 79 |
+
does not exist at runtime
|
| 80 |
+
*/
|
| 81 |
+
private readonly _type!: 'FulfillWithMeta'
|
| 82 |
+
constructor(
|
| 83 |
+
public readonly payload: Payload,
|
| 84 |
+
public readonly meta: FulfilledMeta,
|
| 85 |
+
) {}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/**
|
| 89 |
+
* Serializes an error into a plain object.
|
| 90 |
+
* Reworked from https://github.com/sindresorhus/serialize-error
|
| 91 |
+
*
|
| 92 |
+
* @public
|
| 93 |
+
*/
|
| 94 |
+
export const miniSerializeError = (value: any): SerializedError => {
|
| 95 |
+
if (typeof value === 'object' && value !== null) {
|
| 96 |
+
const simpleError: SerializedError = {}
|
| 97 |
+
for (const property of commonProperties) {
|
| 98 |
+
if (typeof value[property] === 'string') {
|
| 99 |
+
simpleError[property] = value[property]
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
return simpleError
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
return { message: String(value) }
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
export type AsyncThunkConfig = {
|
| 110 |
+
state?: unknown
|
| 111 |
+
dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>
|
| 112 |
+
extra?: unknown
|
| 113 |
+
rejectValue?: unknown
|
| 114 |
+
serializedErrorType?: unknown
|
| 115 |
+
pendingMeta?: unknown
|
| 116 |
+
fulfilledMeta?: unknown
|
| 117 |
+
rejectedMeta?: unknown
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
export type GetState<ThunkApiConfig> = ThunkApiConfig extends {
|
| 121 |
+
state: infer State
|
| 122 |
+
}
|
| 123 |
+
? State
|
| 124 |
+
: unknown
|
| 125 |
+
|
| 126 |
+
type GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }
|
| 127 |
+
? Extra
|
| 128 |
+
: unknown
|
| 129 |
+
type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
|
| 130 |
+
dispatch: infer Dispatch
|
| 131 |
+
}
|
| 132 |
+
? FallbackIfUnknown<
|
| 133 |
+
Dispatch,
|
| 134 |
+
ThunkDispatch<
|
| 135 |
+
GetState<ThunkApiConfig>,
|
| 136 |
+
GetExtra<ThunkApiConfig>,
|
| 137 |
+
UnknownAction
|
| 138 |
+
>
|
| 139 |
+
>
|
| 140 |
+
: ThunkDispatch<
|
| 141 |
+
GetState<ThunkApiConfig>,
|
| 142 |
+
GetExtra<ThunkApiConfig>,
|
| 143 |
+
UnknownAction
|
| 144 |
+
>
|
| 145 |
+
|
| 146 |
+
export type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
|
| 147 |
+
GetState<ThunkApiConfig>,
|
| 148 |
+
GetExtra<ThunkApiConfig>,
|
| 149 |
+
GetDispatch<ThunkApiConfig>,
|
| 150 |
+
GetRejectValue<ThunkApiConfig>,
|
| 151 |
+
GetRejectedMeta<ThunkApiConfig>,
|
| 152 |
+
GetFulfilledMeta<ThunkApiConfig>
|
| 153 |
+
>
|
| 154 |
+
|
| 155 |
+
type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
|
| 156 |
+
rejectValue: infer RejectValue
|
| 157 |
+
}
|
| 158 |
+
? RejectValue
|
| 159 |
+
: unknown
|
| 160 |
+
|
| 161 |
+
type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
|
| 162 |
+
pendingMeta: infer PendingMeta
|
| 163 |
+
}
|
| 164 |
+
? PendingMeta
|
| 165 |
+
: unknown
|
| 166 |
+
|
| 167 |
+
type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
|
| 168 |
+
fulfilledMeta: infer FulfilledMeta
|
| 169 |
+
}
|
| 170 |
+
? FulfilledMeta
|
| 171 |
+
: unknown
|
| 172 |
+
|
| 173 |
+
type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
|
| 174 |
+
rejectedMeta: infer RejectedMeta
|
| 175 |
+
}
|
| 176 |
+
? RejectedMeta
|
| 177 |
+
: unknown
|
| 178 |
+
|
| 179 |
+
type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
|
| 180 |
+
serializedErrorType: infer GetSerializedErrorType
|
| 181 |
+
}
|
| 182 |
+
? GetSerializedErrorType
|
| 183 |
+
: SerializedError
|
| 184 |
+
|
| 185 |
+
type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)
|
| 186 |
+
|
| 187 |
+
/**
|
| 188 |
+
* A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
|
| 189 |
+
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
|
| 190 |
+
*
|
| 191 |
+
* @public
|
| 192 |
+
*/
|
| 193 |
+
export type AsyncThunkPayloadCreatorReturnValue<
|
| 194 |
+
Returned,
|
| 195 |
+
ThunkApiConfig extends AsyncThunkConfig,
|
| 196 |
+
> = MaybePromise<
|
| 197 |
+
| IsUnknown<
|
| 198 |
+
GetFulfilledMeta<ThunkApiConfig>,
|
| 199 |
+
Returned,
|
| 200 |
+
FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>
|
| 201 |
+
>
|
| 202 |
+
| RejectWithValue<
|
| 203 |
+
GetRejectValue<ThunkApiConfig>,
|
| 204 |
+
GetRejectedMeta<ThunkApiConfig>
|
| 205 |
+
>
|
| 206 |
+
>
|
| 207 |
+
/**
|
| 208 |
+
* A type describing the `payloadCreator` argument to `createAsyncThunk`.
|
| 209 |
+
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
|
| 210 |
+
*
|
| 211 |
+
* @public
|
| 212 |
+
*/
|
| 213 |
+
export type AsyncThunkPayloadCreator<
|
| 214 |
+
Returned,
|
| 215 |
+
ThunkArg = void,
|
| 216 |
+
ThunkApiConfig extends AsyncThunkConfig = {},
|
| 217 |
+
> = (
|
| 218 |
+
arg: ThunkArg,
|
| 219 |
+
thunkAPI: GetThunkAPI<ThunkApiConfig>,
|
| 220 |
+
) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>
|
| 221 |
+
|
| 222 |
+
/**
|
| 223 |
+
* A ThunkAction created by `createAsyncThunk`.
|
| 224 |
+
* Dispatching it returns a Promise for either a
|
| 225 |
+
* fulfilled or rejected action.
|
| 226 |
+
* Also, the returned value contains an `abort()` method
|
| 227 |
+
* that allows the asyncAction to be cancelled from the outside.
|
| 228 |
+
*
|
| 229 |
+
* @public
|
| 230 |
+
*/
|
| 231 |
+
export type AsyncThunkAction<
|
| 232 |
+
Returned,
|
| 233 |
+
ThunkArg,
|
| 234 |
+
ThunkApiConfig extends AsyncThunkConfig,
|
| 235 |
+
> = (
|
| 236 |
+
dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,
|
| 237 |
+
getState: () => GetState<ThunkApiConfig>,
|
| 238 |
+
extra: GetExtra<ThunkApiConfig>,
|
| 239 |
+
) => SafePromise<
|
| 240 |
+
| ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>
|
| 241 |
+
| ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>
|
| 242 |
+
> & {
|
| 243 |
+
abort: (reason?: string) => void
|
| 244 |
+
requestId: string
|
| 245 |
+
arg: ThunkArg
|
| 246 |
+
unwrap: () => Promise<Returned>
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
/**
|
| 250 |
+
* Config provided when calling the async thunk action creator.
|
| 251 |
+
*/
|
| 252 |
+
export interface AsyncThunkDispatchConfig {
|
| 253 |
+
/**
|
| 254 |
+
* An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
|
| 255 |
+
*/
|
| 256 |
+
signal?: AbortSignal
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
type AsyncThunkActionCreator<
|
| 260 |
+
Returned,
|
| 261 |
+
ThunkArg,
|
| 262 |
+
ThunkApiConfig extends AsyncThunkConfig,
|
| 263 |
+
> = IsAny<
|
| 264 |
+
ThunkArg,
|
| 265 |
+
// any handling
|
| 266 |
+
(
|
| 267 |
+
arg: ThunkArg,
|
| 268 |
+
config?: AsyncThunkDispatchConfig,
|
| 269 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
|
| 270 |
+
// unknown handling
|
| 271 |
+
unknown extends ThunkArg
|
| 272 |
+
? (
|
| 273 |
+
arg: ThunkArg,
|
| 274 |
+
config?: AsyncThunkDispatchConfig,
|
| 275 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined
|
| 276 |
+
: [ThunkArg] extends [void] | [undefined]
|
| 277 |
+
? (
|
| 278 |
+
arg?: undefined,
|
| 279 |
+
config?: AsyncThunkDispatchConfig,
|
| 280 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void
|
| 281 |
+
: [void] extends [ThunkArg] // make optional
|
| 282 |
+
? (
|
| 283 |
+
arg?: ThunkArg,
|
| 284 |
+
config?: AsyncThunkDispatchConfig,
|
| 285 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined
|
| 286 |
+
: [undefined] extends [ThunkArg]
|
| 287 |
+
? WithStrictNullChecks<
|
| 288 |
+
// with strict nullChecks: make optional
|
| 289 |
+
(
|
| 290 |
+
arg?: ThunkArg,
|
| 291 |
+
config?: AsyncThunkDispatchConfig,
|
| 292 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,
|
| 293 |
+
// without strict null checks this will match everything, so don't make it optional
|
| 294 |
+
(
|
| 295 |
+
arg: ThunkArg,
|
| 296 |
+
config?: AsyncThunkDispatchConfig,
|
| 297 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
|
| 298 |
+
> // default case: normal argument
|
| 299 |
+
: (
|
| 300 |
+
arg: ThunkArg,
|
| 301 |
+
config?: AsyncThunkDispatchConfig,
|
| 302 |
+
) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>
|
| 303 |
+
>
|
| 304 |
+
|
| 305 |
+
/**
|
| 306 |
+
* Options object for `createAsyncThunk`.
|
| 307 |
+
*
|
| 308 |
+
* @public
|
| 309 |
+
*/
|
| 310 |
+
export type AsyncThunkOptions<
|
| 311 |
+
ThunkArg = void,
|
| 312 |
+
ThunkApiConfig extends AsyncThunkConfig = {},
|
| 313 |
+
> = {
|
| 314 |
+
/**
|
| 315 |
+
* A method to control whether the asyncThunk should be executed. Has access to the
|
| 316 |
+
* `arg`, `api.getState()` and `api.extra` arguments.
|
| 317 |
+
*
|
| 318 |
+
* @returns `false` if it should be skipped
|
| 319 |
+
*/
|
| 320 |
+
condition?(
|
| 321 |
+
arg: ThunkArg,
|
| 322 |
+
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
|
| 323 |
+
): MaybePromise<boolean | undefined>
|
| 324 |
+
/**
|
| 325 |
+
* If `condition` returns `false`, the asyncThunk will be skipped.
|
| 326 |
+
* This option allows you to control whether a `rejected` action with `meta.condition == false`
|
| 327 |
+
* will be dispatched or not.
|
| 328 |
+
*
|
| 329 |
+
* @default `false`
|
| 330 |
+
*/
|
| 331 |
+
dispatchConditionRejection?: boolean
|
| 332 |
+
|
| 333 |
+
serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>
|
| 334 |
+
|
| 335 |
+
/**
|
| 336 |
+
* A function to use when generating the `requestId` for the request sequence.
|
| 337 |
+
*
|
| 338 |
+
* @default `nanoid`
|
| 339 |
+
*/
|
| 340 |
+
idGenerator?: (arg: ThunkArg) => string
|
| 341 |
+
} & IsUnknown<
|
| 342 |
+
GetPendingMeta<ThunkApiConfig>,
|
| 343 |
+
{
|
| 344 |
+
/**
|
| 345 |
+
* A method to generate additional properties to be added to `meta` of the pending action.
|
| 346 |
+
*
|
| 347 |
+
* Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
|
| 348 |
+
* Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
|
| 349 |
+
*/
|
| 350 |
+
getPendingMeta?(
|
| 351 |
+
base: {
|
| 352 |
+
arg: ThunkArg
|
| 353 |
+
requestId: string
|
| 354 |
+
},
|
| 355 |
+
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
|
| 356 |
+
): GetPendingMeta<ThunkApiConfig>
|
| 357 |
+
},
|
| 358 |
+
{
|
| 359 |
+
/**
|
| 360 |
+
* A method to generate additional properties to be added to `meta` of the pending action.
|
| 361 |
+
*/
|
| 362 |
+
getPendingMeta(
|
| 363 |
+
base: {
|
| 364 |
+
arg: ThunkArg
|
| 365 |
+
requestId: string
|
| 366 |
+
},
|
| 367 |
+
api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,
|
| 368 |
+
): GetPendingMeta<ThunkApiConfig>
|
| 369 |
+
}
|
| 370 |
+
>
|
| 371 |
+
|
| 372 |
+
export type AsyncThunkPendingActionCreator<
|
| 373 |
+
ThunkArg,
|
| 374 |
+
ThunkApiConfig = {},
|
| 375 |
+
> = ActionCreatorWithPreparedPayload<
|
| 376 |
+
[string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],
|
| 377 |
+
undefined,
|
| 378 |
+
string,
|
| 379 |
+
never,
|
| 380 |
+
{
|
| 381 |
+
arg: ThunkArg
|
| 382 |
+
requestId: string
|
| 383 |
+
requestStatus: 'pending'
|
| 384 |
+
} & GetPendingMeta<ThunkApiConfig>
|
| 385 |
+
>
|
| 386 |
+
|
| 387 |
+
export type AsyncThunkRejectedActionCreator<
|
| 388 |
+
ThunkArg,
|
| 389 |
+
ThunkApiConfig = {},
|
| 390 |
+
> = ActionCreatorWithPreparedPayload<
|
| 391 |
+
[
|
| 392 |
+
Error | null,
|
| 393 |
+
string,
|
| 394 |
+
ThunkArg,
|
| 395 |
+
GetRejectValue<ThunkApiConfig>?,
|
| 396 |
+
GetRejectedMeta<ThunkApiConfig>?,
|
| 397 |
+
],
|
| 398 |
+
GetRejectValue<ThunkApiConfig> | undefined,
|
| 399 |
+
string,
|
| 400 |
+
GetSerializedErrorType<ThunkApiConfig>,
|
| 401 |
+
{
|
| 402 |
+
arg: ThunkArg
|
| 403 |
+
requestId: string
|
| 404 |
+
requestStatus: 'rejected'
|
| 405 |
+
aborted: boolean
|
| 406 |
+
condition: boolean
|
| 407 |
+
} & (
|
| 408 |
+
| ({ rejectedWithValue: false } & {
|
| 409 |
+
[K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined
|
| 410 |
+
})
|
| 411 |
+
| ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)
|
| 412 |
+
)
|
| 413 |
+
>
|
| 414 |
+
|
| 415 |
+
export type AsyncThunkFulfilledActionCreator<
|
| 416 |
+
Returned,
|
| 417 |
+
ThunkArg,
|
| 418 |
+
ThunkApiConfig = {},
|
| 419 |
+
> = ActionCreatorWithPreparedPayload<
|
| 420 |
+
[Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],
|
| 421 |
+
Returned,
|
| 422 |
+
string,
|
| 423 |
+
never,
|
| 424 |
+
{
|
| 425 |
+
arg: ThunkArg
|
| 426 |
+
requestId: string
|
| 427 |
+
requestStatus: 'fulfilled'
|
| 428 |
+
} & GetFulfilledMeta<ThunkApiConfig>
|
| 429 |
+
>
|
| 430 |
+
|
| 431 |
+
/**
|
| 432 |
+
* A type describing the return value of `createAsyncThunk`.
|
| 433 |
+
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
|
| 434 |
+
*
|
| 435 |
+
* @public
|
| 436 |
+
*/
|
| 437 |
+
export type AsyncThunk<
|
| 438 |
+
Returned,
|
| 439 |
+
ThunkArg,
|
| 440 |
+
ThunkApiConfig extends AsyncThunkConfig,
|
| 441 |
+
> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
|
| 442 |
+
pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>
|
| 443 |
+
rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
|
| 444 |
+
fulfilled: AsyncThunkFulfilledActionCreator<
|
| 445 |
+
Returned,
|
| 446 |
+
ThunkArg,
|
| 447 |
+
ThunkApiConfig
|
| 448 |
+
>
|
| 449 |
+
// matchSettled?
|
| 450 |
+
settled: (
|
| 451 |
+
action: any,
|
| 452 |
+
) => action is ReturnType<
|
| 453 |
+
| AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>
|
| 454 |
+
| AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>
|
| 455 |
+
>
|
| 456 |
+
typePrefix: string
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
export type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<
|
| 460 |
+
NewConfig & Omit<OldConfig, keyof NewConfig>
|
| 461 |
+
>
|
| 462 |
+
|
| 463 |
+
export type CreateAsyncThunkFunction<
|
| 464 |
+
CurriedThunkApiConfig extends AsyncThunkConfig,
|
| 465 |
+
> = {
|
| 466 |
+
/**
|
| 467 |
+
*
|
| 468 |
+
* @param typePrefix
|
| 469 |
+
* @param payloadCreator
|
| 470 |
+
* @param options
|
| 471 |
+
*
|
| 472 |
+
* @public
|
| 473 |
+
*/
|
| 474 |
+
// separate signature without `AsyncThunkConfig` for better inference
|
| 475 |
+
<Returned, ThunkArg = void>(
|
| 476 |
+
typePrefix: string,
|
| 477 |
+
payloadCreator: AsyncThunkPayloadCreator<
|
| 478 |
+
Returned,
|
| 479 |
+
ThunkArg,
|
| 480 |
+
CurriedThunkApiConfig
|
| 481 |
+
>,
|
| 482 |
+
options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,
|
| 483 |
+
): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>
|
| 484 |
+
|
| 485 |
+
/**
|
| 486 |
+
*
|
| 487 |
+
* @param typePrefix
|
| 488 |
+
* @param payloadCreator
|
| 489 |
+
* @param options
|
| 490 |
+
*
|
| 491 |
+
* @public
|
| 492 |
+
*/
|
| 493 |
+
<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(
|
| 494 |
+
typePrefix: string,
|
| 495 |
+
payloadCreator: AsyncThunkPayloadCreator<
|
| 496 |
+
Returned,
|
| 497 |
+
ThunkArg,
|
| 498 |
+
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
|
| 499 |
+
>,
|
| 500 |
+
options?: AsyncThunkOptions<
|
| 501 |
+
ThunkArg,
|
| 502 |
+
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
|
| 503 |
+
>,
|
| 504 |
+
): AsyncThunk<
|
| 505 |
+
Returned,
|
| 506 |
+
ThunkArg,
|
| 507 |
+
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
|
| 508 |
+
>
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> =
|
| 512 |
+
CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
|
| 513 |
+
withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<
|
| 514 |
+
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
|
| 515 |
+
>
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
const externalAbortMessage = 'External signal was aborted'
|
| 519 |
+
|
| 520 |
+
export const createAsyncThunk = /* @__PURE__ */ (() => {
|
| 521 |
+
function createAsyncThunk<
|
| 522 |
+
Returned,
|
| 523 |
+
ThunkArg,
|
| 524 |
+
ThunkApiConfig extends AsyncThunkConfig,
|
| 525 |
+
>(
|
| 526 |
+
typePrefix: string,
|
| 527 |
+
payloadCreator: AsyncThunkPayloadCreator<
|
| 528 |
+
Returned,
|
| 529 |
+
ThunkArg,
|
| 530 |
+
ThunkApiConfig
|
| 531 |
+
>,
|
| 532 |
+
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,
|
| 533 |
+
): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
|
| 534 |
+
type RejectedValue = GetRejectValue<ThunkApiConfig>
|
| 535 |
+
type PendingMeta = GetPendingMeta<ThunkApiConfig>
|
| 536 |
+
type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>
|
| 537 |
+
type RejectedMeta = GetRejectedMeta<ThunkApiConfig>
|
| 538 |
+
|
| 539 |
+
const fulfilled: AsyncThunkFulfilledActionCreator<
|
| 540 |
+
Returned,
|
| 541 |
+
ThunkArg,
|
| 542 |
+
ThunkApiConfig
|
| 543 |
+
> = createAction(
|
| 544 |
+
typePrefix + '/fulfilled',
|
| 545 |
+
(
|
| 546 |
+
payload: Returned,
|
| 547 |
+
requestId: string,
|
| 548 |
+
arg: ThunkArg,
|
| 549 |
+
meta?: FulfilledMeta,
|
| 550 |
+
) => ({
|
| 551 |
+
payload,
|
| 552 |
+
meta: {
|
| 553 |
+
...((meta as any) || {}),
|
| 554 |
+
arg,
|
| 555 |
+
requestId,
|
| 556 |
+
requestStatus: 'fulfilled' as const,
|
| 557 |
+
},
|
| 558 |
+
}),
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =
|
| 562 |
+
createAction(
|
| 563 |
+
typePrefix + '/pending',
|
| 564 |
+
(requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({
|
| 565 |
+
payload: undefined,
|
| 566 |
+
meta: {
|
| 567 |
+
...((meta as any) || {}),
|
| 568 |
+
arg,
|
| 569 |
+
requestId,
|
| 570 |
+
requestStatus: 'pending' as const,
|
| 571 |
+
},
|
| 572 |
+
}),
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =
|
| 576 |
+
createAction(
|
| 577 |
+
typePrefix + '/rejected',
|
| 578 |
+
(
|
| 579 |
+
error: Error | null,
|
| 580 |
+
requestId: string,
|
| 581 |
+
arg: ThunkArg,
|
| 582 |
+
payload?: RejectedValue,
|
| 583 |
+
meta?: RejectedMeta,
|
| 584 |
+
) => ({
|
| 585 |
+
payload,
|
| 586 |
+
error: ((options && options.serializeError) || miniSerializeError)(
|
| 587 |
+
error || 'Rejected',
|
| 588 |
+
) as GetSerializedErrorType<ThunkApiConfig>,
|
| 589 |
+
meta: {
|
| 590 |
+
...((meta as any) || {}),
|
| 591 |
+
arg,
|
| 592 |
+
requestId,
|
| 593 |
+
rejectedWithValue: !!payload,
|
| 594 |
+
requestStatus: 'rejected' as const,
|
| 595 |
+
aborted: error?.name === 'AbortError',
|
| 596 |
+
condition: error?.name === 'ConditionError',
|
| 597 |
+
},
|
| 598 |
+
}),
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
function actionCreator(
|
| 602 |
+
arg: ThunkArg,
|
| 603 |
+
{ signal }: AsyncThunkDispatchConfig = {},
|
| 604 |
+
): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {
|
| 605 |
+
return (dispatch, getState, extra) => {
|
| 606 |
+
const requestId = options?.idGenerator
|
| 607 |
+
? options.idGenerator(arg)
|
| 608 |
+
: nanoid()
|
| 609 |
+
|
| 610 |
+
const abortController = new AbortController()
|
| 611 |
+
let abortHandler: (() => void) | undefined
|
| 612 |
+
let abortReason: string | undefined
|
| 613 |
+
|
| 614 |
+
function abort(reason?: string) {
|
| 615 |
+
abortReason = reason
|
| 616 |
+
abortController.abort()
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
if (signal) {
|
| 620 |
+
if (signal.aborted) {
|
| 621 |
+
abort(externalAbortMessage)
|
| 622 |
+
} else {
|
| 623 |
+
signal.addEventListener(
|
| 624 |
+
'abort',
|
| 625 |
+
() => abort(externalAbortMessage),
|
| 626 |
+
{ once: true },
|
| 627 |
+
)
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
const promise = (async function () {
|
| 632 |
+
let finalAction: ReturnType<typeof fulfilled | typeof rejected>
|
| 633 |
+
try {
|
| 634 |
+
let conditionResult = options?.condition?.(arg, { getState, extra })
|
| 635 |
+
if (isThenable(conditionResult)) {
|
| 636 |
+
conditionResult = await conditionResult
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
if (conditionResult === false || abortController.signal.aborted) {
|
| 640 |
+
// eslint-disable-next-line no-throw-literal
|
| 641 |
+
throw {
|
| 642 |
+
name: 'ConditionError',
|
| 643 |
+
message: 'Aborted due to condition callback returning false.',
|
| 644 |
+
}
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
const abortedPromise = new Promise<never>((_, reject) => {
|
| 648 |
+
abortHandler = () => {
|
| 649 |
+
reject({
|
| 650 |
+
name: 'AbortError',
|
| 651 |
+
message: abortReason || 'Aborted',
|
| 652 |
+
})
|
| 653 |
+
}
|
| 654 |
+
abortController.signal.addEventListener('abort', abortHandler, {
|
| 655 |
+
once: true,
|
| 656 |
+
})
|
| 657 |
+
})
|
| 658 |
+
dispatch(
|
| 659 |
+
pending(
|
| 660 |
+
requestId,
|
| 661 |
+
arg,
|
| 662 |
+
options?.getPendingMeta?.(
|
| 663 |
+
{ requestId, arg },
|
| 664 |
+
{ getState, extra },
|
| 665 |
+
),
|
| 666 |
+
) as any,
|
| 667 |
+
)
|
| 668 |
+
finalAction = await Promise.race([
|
| 669 |
+
abortedPromise,
|
| 670 |
+
Promise.resolve(
|
| 671 |
+
payloadCreator(arg, {
|
| 672 |
+
dispatch,
|
| 673 |
+
getState,
|
| 674 |
+
extra,
|
| 675 |
+
requestId,
|
| 676 |
+
signal: abortController.signal,
|
| 677 |
+
abort,
|
| 678 |
+
rejectWithValue: ((
|
| 679 |
+
value: RejectedValue,
|
| 680 |
+
meta?: RejectedMeta,
|
| 681 |
+
) => {
|
| 682 |
+
return new RejectWithValue(value, meta)
|
| 683 |
+
}) as any,
|
| 684 |
+
fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {
|
| 685 |
+
return new FulfillWithMeta(value, meta)
|
| 686 |
+
}) as any,
|
| 687 |
+
}),
|
| 688 |
+
).then((result) => {
|
| 689 |
+
if (result instanceof RejectWithValue) {
|
| 690 |
+
throw result
|
| 691 |
+
}
|
| 692 |
+
if (result instanceof FulfillWithMeta) {
|
| 693 |
+
return fulfilled(result.payload, requestId, arg, result.meta)
|
| 694 |
+
}
|
| 695 |
+
return fulfilled(result as any, requestId, arg)
|
| 696 |
+
}),
|
| 697 |
+
])
|
| 698 |
+
} catch (err) {
|
| 699 |
+
finalAction =
|
| 700 |
+
err instanceof RejectWithValue
|
| 701 |
+
? rejected(null, requestId, arg, err.payload, err.meta)
|
| 702 |
+
: rejected(err as any, requestId, arg)
|
| 703 |
+
} finally {
|
| 704 |
+
if (abortHandler) {
|
| 705 |
+
abortController.signal.removeEventListener('abort', abortHandler)
|
| 706 |
+
}
|
| 707 |
+
}
|
| 708 |
+
// We dispatch the result action _after_ the catch, to avoid having any errors
|
| 709 |
+
// here get swallowed by the try/catch block,
|
| 710 |
+
// per https://twitter.com/dan_abramov/status/770914221638942720
|
| 711 |
+
// and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks
|
| 712 |
+
|
| 713 |
+
const skipDispatch =
|
| 714 |
+
options &&
|
| 715 |
+
!options.dispatchConditionRejection &&
|
| 716 |
+
rejected.match(finalAction) &&
|
| 717 |
+
(finalAction as any).meta.condition
|
| 718 |
+
|
| 719 |
+
if (!skipDispatch) {
|
| 720 |
+
dispatch(finalAction as any)
|
| 721 |
+
}
|
| 722 |
+
return finalAction
|
| 723 |
+
})()
|
| 724 |
+
return Object.assign(promise as SafePromise<any>, {
|
| 725 |
+
abort,
|
| 726 |
+
requestId,
|
| 727 |
+
arg,
|
| 728 |
+
unwrap() {
|
| 729 |
+
return promise.then<any>(unwrapResult)
|
| 730 |
+
},
|
| 731 |
+
})
|
| 732 |
+
}
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
return Object.assign(
|
| 736 |
+
actionCreator as AsyncThunkActionCreator<
|
| 737 |
+
Returned,
|
| 738 |
+
ThunkArg,
|
| 739 |
+
ThunkApiConfig
|
| 740 |
+
>,
|
| 741 |
+
{
|
| 742 |
+
pending,
|
| 743 |
+
rejected,
|
| 744 |
+
fulfilled,
|
| 745 |
+
settled: isAnyOf(rejected, fulfilled),
|
| 746 |
+
typePrefix,
|
| 747 |
+
},
|
| 748 |
+
)
|
| 749 |
+
}
|
| 750 |
+
createAsyncThunk.withTypes = () => createAsyncThunk
|
| 751 |
+
|
| 752 |
+
return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>
|
| 753 |
+
})()
|
| 754 |
+
|
| 755 |
+
interface UnwrappableAction {
|
| 756 |
+
payload: any
|
| 757 |
+
meta?: any
|
| 758 |
+
error?: any
|
| 759 |
+
}
|
| 760 |
+
|
| 761 |
+
type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<
|
| 762 |
+
T,
|
| 763 |
+
{ error: any }
|
| 764 |
+
>['payload']
|
| 765 |
+
|
| 766 |
+
/**
|
| 767 |
+
* @public
|
| 768 |
+
*/
|
| 769 |
+
export function unwrapResult<R extends UnwrappableAction>(
|
| 770 |
+
action: R,
|
| 771 |
+
): UnwrappedActionPayload<R> {
|
| 772 |
+
if (action.meta && action.meta.rejectedWithValue) {
|
| 773 |
+
throw action.payload
|
| 774 |
+
}
|
| 775 |
+
if (action.error) {
|
| 776 |
+
throw action.error
|
| 777 |
+
}
|
| 778 |
+
return action.payload
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
type WithStrictNullChecks<True, False> = undefined extends boolean
|
| 782 |
+
? False
|
| 783 |
+
: True
|
| 784 |
+
|
| 785 |
+
function isThenable(value: any): value is PromiseLike<any> {
|
| 786 |
+
return (
|
| 787 |
+
value !== null &&
|
| 788 |
+
typeof value === 'object' &&
|
| 789 |
+
typeof value.then === 'function'
|
| 790 |
+
)
|
| 791 |
+
}
|
node_modules/@reduxjs/toolkit/src/createDraftSafeSelector.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { current, isDraft } from './immerImports'
|
| 2 |
+
import { createSelectorCreator, weakMapMemoize } from './reselectImports'
|
| 3 |
+
|
| 4 |
+
export const createDraftSafeSelectorCreator: typeof createSelectorCreator = (
|
| 5 |
+
...args: unknown[]
|
| 6 |
+
) => {
|
| 7 |
+
const createSelector = (createSelectorCreator as any)(...args)
|
| 8 |
+
const createDraftSafeSelector = Object.assign(
|
| 9 |
+
(...args: unknown[]) => {
|
| 10 |
+
const selector = createSelector(...args)
|
| 11 |
+
const wrappedSelector = (value: unknown, ...rest: unknown[]) =>
|
| 12 |
+
selector(isDraft(value) ? current(value) : value, ...rest)
|
| 13 |
+
Object.assign(wrappedSelector, selector)
|
| 14 |
+
return wrappedSelector as any
|
| 15 |
+
},
|
| 16 |
+
{ withTypes: () => createDraftSafeSelector },
|
| 17 |
+
)
|
| 18 |
+
return createDraftSafeSelector
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
/**
|
| 22 |
+
* "Draft-Safe" version of `reselect`'s `createSelector`:
|
| 23 |
+
* If an `immer`-drafted object is passed into the resulting selector's first argument,
|
| 24 |
+
* the selector will act on the current draft value, instead of returning a cached value
|
| 25 |
+
* that might be possibly outdated if the draft has been modified since.
|
| 26 |
+
* @public
|
| 27 |
+
*/
|
| 28 |
+
export const createDraftSafeSelector =
|
| 29 |
+
/* @__PURE__ */
|
| 30 |
+
createDraftSafeSelectorCreator(weakMapMemoize)
|
node_modules/@reduxjs/toolkit/src/createReducer.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 3 |
+
import { createNextState, isDraft, isDraftable } from './immerImports'
|
| 4 |
+
import type { ActionReducerMapBuilder } from './mapBuilders'
|
| 5 |
+
import { executeReducerBuilderCallback } from './mapBuilders'
|
| 6 |
+
import type { TypeGuard } from './tsHelpers'
|
| 7 |
+
import { freezeDraftable } from './utils'
|
| 8 |
+
|
| 9 |
+
/**
|
| 10 |
+
* Defines a mapping from action types to corresponding action object shapes.
|
| 11 |
+
*
|
| 12 |
+
* @deprecated This should not be used manually - it is only used for internal
|
| 13 |
+
* inference purposes and should not have any further value.
|
| 14 |
+
* It might be removed in the future.
|
| 15 |
+
* @public
|
| 16 |
+
*/
|
| 17 |
+
export type Actions<T extends keyof any = string> = Record<T, Action>
|
| 18 |
+
|
| 19 |
+
export type ActionMatcherDescription<S, A extends Action> = {
|
| 20 |
+
matcher: TypeGuard<A>
|
| 21 |
+
reducer: CaseReducer<S, NoInfer<A>>
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
export type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<
|
| 25 |
+
ActionMatcherDescription<S, any>
|
| 26 |
+
>
|
| 27 |
+
|
| 28 |
+
export type ActionMatcherDescriptionCollection<S> = Array<
|
| 29 |
+
ActionMatcherDescription<S, any>
|
| 30 |
+
>
|
| 31 |
+
|
| 32 |
+
/**
|
| 33 |
+
* A *case reducer* is a reducer function for a specific action type. Case
|
| 34 |
+
* reducers can be composed to full reducers using `createReducer()`.
|
| 35 |
+
*
|
| 36 |
+
* Unlike a normal Redux reducer, a case reducer is never called with an
|
| 37 |
+
* `undefined` state to determine the initial state. Instead, the initial
|
| 38 |
+
* state is explicitly specified as an argument to `createReducer()`.
|
| 39 |
+
*
|
| 40 |
+
* In addition, a case reducer can choose to mutate the passed-in `state`
|
| 41 |
+
* value directly instead of returning a new state. This does not actually
|
| 42 |
+
* cause the store state to be mutated directly; instead, thanks to
|
| 43 |
+
* [immer](https://github.com/mweststrate/immer), the mutations are
|
| 44 |
+
* translated to copy operations that result in a new state.
|
| 45 |
+
*
|
| 46 |
+
* @public
|
| 47 |
+
*/
|
| 48 |
+
export type CaseReducer<S = any, A extends Action = UnknownAction> = (
|
| 49 |
+
state: Draft<S>,
|
| 50 |
+
action: A,
|
| 51 |
+
) => NoInfer<S> | void | Draft<NoInfer<S>>
|
| 52 |
+
|
| 53 |
+
/**
|
| 54 |
+
* A mapping from action types to case reducers for `createReducer()`.
|
| 55 |
+
*
|
| 56 |
+
* @deprecated This should not be used manually - it is only used
|
| 57 |
+
* for internal inference purposes and using it manually
|
| 58 |
+
* would lead to type erasure.
|
| 59 |
+
* It might be removed in the future.
|
| 60 |
+
* @public
|
| 61 |
+
*/
|
| 62 |
+
export type CaseReducers<S, AS extends Actions> = {
|
| 63 |
+
[T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
export type NotFunction<T> = T extends Function ? never : T
|
| 67 |
+
|
| 68 |
+
function isStateFunction<S>(x: unknown): x is () => S {
|
| 69 |
+
return typeof x === 'function'
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
export type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
|
| 73 |
+
getInitialState: () => S
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/**
|
| 77 |
+
* A utility function that allows defining a reducer as a mapping from action
|
| 78 |
+
* type to *case reducer* functions that handle these action types. The
|
| 79 |
+
* reducer's initial state is passed as the first argument.
|
| 80 |
+
*
|
| 81 |
+
* @remarks
|
| 82 |
+
* The body of every case reducer is implicitly wrapped with a call to
|
| 83 |
+
* `produce()` from the [immer](https://github.com/mweststrate/immer) library.
|
| 84 |
+
* This means that rather than returning a new state object, you can also
|
| 85 |
+
* mutate the passed-in state object directly; these mutations will then be
|
| 86 |
+
* automatically and efficiently translated into copies, giving you both
|
| 87 |
+
* convenience and immutability.
|
| 88 |
+
*
|
| 89 |
+
* @overloadSummary
|
| 90 |
+
* This function accepts a callback that receives a `builder` object as its argument.
|
| 91 |
+
* That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
|
| 92 |
+
* called to define what actions this reducer will handle.
|
| 93 |
+
*
|
| 94 |
+
* @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
|
| 95 |
+
* @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
|
| 96 |
+
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
|
| 97 |
+
* @example
|
| 98 |
+
* ```ts
|
| 99 |
+
* import type { PayloadAction, UnknownAction } from '@reduxjs/toolkit';
|
| 100 |
+
* import { createAction, createReducer } from '@reduxjs/toolkit';
|
| 101 |
+
*
|
| 102 |
+
* const increment = createAction<number>('increment');
|
| 103 |
+
* const decrement = createAction<number>('decrement');
|
| 104 |
+
*
|
| 105 |
+
* function isActionWithNumberPayload(
|
| 106 |
+
* action: UnknownAction,
|
| 107 |
+
* ): action is PayloadAction<number> {
|
| 108 |
+
* return typeof action.payload === 'number';
|
| 109 |
+
* }
|
| 110 |
+
*
|
| 111 |
+
* const reducer = createReducer(
|
| 112 |
+
* {
|
| 113 |
+
* counter: 0,
|
| 114 |
+
* sumOfNumberPayloads: 0,
|
| 115 |
+
* unhandledActions: 0,
|
| 116 |
+
* },
|
| 117 |
+
* (builder) => {
|
| 118 |
+
* builder
|
| 119 |
+
* .addCase(increment, (state, action) => {
|
| 120 |
+
* // action is inferred correctly here
|
| 121 |
+
* state.counter += action.payload;
|
| 122 |
+
* })
|
| 123 |
+
* // You can chain calls, or have separate `builder.addCase()` lines each time
|
| 124 |
+
* .addCase(decrement, (state, action) => {
|
| 125 |
+
* state.counter -= action.payload;
|
| 126 |
+
* })
|
| 127 |
+
* // You can apply a "matcher function" to incoming actions
|
| 128 |
+
* .addMatcher(isActionWithNumberPayload, (state, action) => {})
|
| 129 |
+
* // and provide a default case if no other handlers matched
|
| 130 |
+
* .addDefaultCase((state, action) => {});
|
| 131 |
+
* },
|
| 132 |
+
* );
|
| 133 |
+
* ```
|
| 134 |
+
* @public
|
| 135 |
+
*/
|
| 136 |
+
export function createReducer<S extends NotFunction<any>>(
|
| 137 |
+
initialState: S | (() => S),
|
| 138 |
+
mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void,
|
| 139 |
+
): ReducerWithInitialState<S> {
|
| 140 |
+
if (process.env.NODE_ENV !== 'production') {
|
| 141 |
+
if (typeof mapOrBuilderCallback === 'object') {
|
| 142 |
+
throw new Error(
|
| 143 |
+
"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer",
|
| 144 |
+
)
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =
|
| 149 |
+
executeReducerBuilderCallback(mapOrBuilderCallback)
|
| 150 |
+
|
| 151 |
+
// Ensure the initial state gets frozen either way (if draftable)
|
| 152 |
+
let getInitialState: () => S
|
| 153 |
+
if (isStateFunction(initialState)) {
|
| 154 |
+
getInitialState = () => freezeDraftable(initialState())
|
| 155 |
+
} else {
|
| 156 |
+
const frozenInitialState = freezeDraftable(initialState)
|
| 157 |
+
getInitialState = () => frozenInitialState
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
function reducer(state = getInitialState(), action: any): S {
|
| 161 |
+
let caseReducers = [
|
| 162 |
+
actionsMap[action.type],
|
| 163 |
+
...finalActionMatchers
|
| 164 |
+
.filter(({ matcher }) => matcher(action))
|
| 165 |
+
.map(({ reducer }) => reducer),
|
| 166 |
+
]
|
| 167 |
+
if (caseReducers.filter((cr) => !!cr).length === 0) {
|
| 168 |
+
caseReducers = [finalDefaultCaseReducer]
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
return caseReducers.reduce((previousState, caseReducer): S => {
|
| 172 |
+
if (caseReducer) {
|
| 173 |
+
if (isDraft(previousState)) {
|
| 174 |
+
// If it's already a draft, we must already be inside a `createNextState` call,
|
| 175 |
+
// likely because this is being wrapped in `createReducer`, `createSlice`, or nested
|
| 176 |
+
// inside an existing draft. It's safe to just pass the draft to the mutator.
|
| 177 |
+
const draft = previousState as Draft<S> // We can assume this is already a draft
|
| 178 |
+
const result = caseReducer(draft, action)
|
| 179 |
+
|
| 180 |
+
if (result === undefined) {
|
| 181 |
+
return previousState
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
return result as S
|
| 185 |
+
} else if (!isDraftable(previousState)) {
|
| 186 |
+
// If state is not draftable (ex: a primitive, such as 0), we want to directly
|
| 187 |
+
// return the caseReducer func and not wrap it with produce.
|
| 188 |
+
const result = caseReducer(previousState as any, action)
|
| 189 |
+
|
| 190 |
+
if (result === undefined) {
|
| 191 |
+
if (previousState === null) {
|
| 192 |
+
return previousState
|
| 193 |
+
}
|
| 194 |
+
throw Error(
|
| 195 |
+
'A case reducer on a non-draftable value must not return undefined',
|
| 196 |
+
)
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
return result as S
|
| 200 |
+
} else {
|
| 201 |
+
// @ts-ignore createNextState() produces an Immutable<Draft<S>> rather
|
| 202 |
+
// than an Immutable<S>, and TypeScript cannot find out how to reconcile
|
| 203 |
+
// these two types.
|
| 204 |
+
return createNextState(previousState, (draft: Draft<S>) => {
|
| 205 |
+
return caseReducer(draft, action)
|
| 206 |
+
})
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
return previousState
|
| 211 |
+
}, state)
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
reducer.getInitialState = getInitialState
|
| 215 |
+
|
| 216 |
+
return reducer as ReducerWithInitialState<S>
|
| 217 |
+
}
|
node_modules/@reduxjs/toolkit/src/createSlice.ts
ADDED
|
@@ -0,0 +1,1079 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Action, Reducer, UnknownAction } from 'redux'
|
| 2 |
+
import type { Selector } from 'reselect'
|
| 3 |
+
import type { InjectConfig } from './combineSlices'
|
| 4 |
+
import type {
|
| 5 |
+
ActionCreatorWithoutPayload,
|
| 6 |
+
PayloadAction,
|
| 7 |
+
PayloadActionCreator,
|
| 8 |
+
PrepareAction,
|
| 9 |
+
_ActionCreatorWithPreparedPayload,
|
| 10 |
+
} from './createAction'
|
| 11 |
+
import { createAction } from './createAction'
|
| 12 |
+
import type {
|
| 13 |
+
AsyncThunk,
|
| 14 |
+
AsyncThunkConfig,
|
| 15 |
+
AsyncThunkOptions,
|
| 16 |
+
AsyncThunkPayloadCreator,
|
| 17 |
+
OverrideThunkApiConfigs,
|
| 18 |
+
} from './createAsyncThunk'
|
| 19 |
+
import { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk'
|
| 20 |
+
import type {
|
| 21 |
+
ActionMatcherDescriptionCollection,
|
| 22 |
+
CaseReducer,
|
| 23 |
+
ReducerWithInitialState,
|
| 24 |
+
} from './createReducer'
|
| 25 |
+
import { createReducer } from './createReducer'
|
| 26 |
+
import type {
|
| 27 |
+
ActionReducerMapBuilder,
|
| 28 |
+
AsyncThunkReducers,
|
| 29 |
+
TypedActionCreator,
|
| 30 |
+
} from './mapBuilders'
|
| 31 |
+
import { executeReducerBuilderCallback } from './mapBuilders'
|
| 32 |
+
import type { Id, TypeGuard } from './tsHelpers'
|
| 33 |
+
import { getOrInsertComputed } from './utils'
|
| 34 |
+
|
| 35 |
+
const asyncThunkSymbol = /* @__PURE__ */ Symbol.for(
|
| 36 |
+
'rtk-slice-createasyncthunk',
|
| 37 |
+
)
|
| 38 |
+
// type is annotated because it's too long to infer
|
| 39 |
+
export const asyncThunkCreator: {
|
| 40 |
+
[asyncThunkSymbol]: typeof _createAsyncThunk
|
| 41 |
+
} = {
|
| 42 |
+
[asyncThunkSymbol]: _createAsyncThunk,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
|
| 46 |
+
reducerPath?: NewReducerPath
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
/**
|
| 50 |
+
* The return value of `createSlice`
|
| 51 |
+
*
|
| 52 |
+
* @public
|
| 53 |
+
*/
|
| 54 |
+
export interface Slice<
|
| 55 |
+
State = any,
|
| 56 |
+
CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
|
| 57 |
+
Name extends string = string,
|
| 58 |
+
ReducerPath extends string = Name,
|
| 59 |
+
Selectors extends SliceSelectors<State> = SliceSelectors<State>,
|
| 60 |
+
> {
|
| 61 |
+
/**
|
| 62 |
+
* The slice name.
|
| 63 |
+
*/
|
| 64 |
+
name: Name
|
| 65 |
+
|
| 66 |
+
/**
|
| 67 |
+
* The slice reducer path.
|
| 68 |
+
*/
|
| 69 |
+
reducerPath: ReducerPath
|
| 70 |
+
|
| 71 |
+
/**
|
| 72 |
+
* The slice's reducer.
|
| 73 |
+
*/
|
| 74 |
+
reducer: Reducer<State>
|
| 75 |
+
|
| 76 |
+
/**
|
| 77 |
+
* Action creators for the types of actions that are handled by the slice
|
| 78 |
+
* reducer.
|
| 79 |
+
*/
|
| 80 |
+
actions: CaseReducerActions<CaseReducers, Name>
|
| 81 |
+
|
| 82 |
+
/**
|
| 83 |
+
* The individual case reducer functions that were passed in the `reducers` parameter.
|
| 84 |
+
* This enables reuse and testing if they were defined inline when calling `createSlice`.
|
| 85 |
+
*/
|
| 86 |
+
caseReducers: SliceDefinedCaseReducers<CaseReducers>
|
| 87 |
+
|
| 88 |
+
/**
|
| 89 |
+
* Provides access to the initial state value given to the slice.
|
| 90 |
+
* If a lazy state initializer was provided, it will be called and a fresh value returned.
|
| 91 |
+
*/
|
| 92 |
+
getInitialState: () => State
|
| 93 |
+
|
| 94 |
+
/**
|
| 95 |
+
* Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
|
| 96 |
+
*/
|
| 97 |
+
getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>
|
| 98 |
+
|
| 99 |
+
/**
|
| 100 |
+
* Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
|
| 101 |
+
*/
|
| 102 |
+
getSelectors<RootState>(
|
| 103 |
+
selectState: (rootState: RootState) => State,
|
| 104 |
+
): Id<SliceDefinedSelectors<State, Selectors, RootState>>
|
| 105 |
+
|
| 106 |
+
/**
|
| 107 |
+
* Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
|
| 108 |
+
*
|
| 109 |
+
* Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
|
| 110 |
+
*/
|
| 111 |
+
get selectors(): Id<
|
| 112 |
+
SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>
|
| 113 |
+
>
|
| 114 |
+
|
| 115 |
+
/**
|
| 116 |
+
* Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
|
| 117 |
+
*/
|
| 118 |
+
injectInto<NewReducerPath extends string = ReducerPath>(
|
| 119 |
+
this: this,
|
| 120 |
+
injectable: {
|
| 121 |
+
inject: (
|
| 122 |
+
slice: { reducerPath: string; reducer: Reducer },
|
| 123 |
+
config?: InjectConfig,
|
| 124 |
+
) => void
|
| 125 |
+
},
|
| 126 |
+
config?: InjectIntoConfig<NewReducerPath>,
|
| 127 |
+
): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>
|
| 128 |
+
|
| 129 |
+
/**
|
| 130 |
+
* Select the slice state, using the slice's current reducerPath.
|
| 131 |
+
*
|
| 132 |
+
* Will throw an error if slice is not found.
|
| 133 |
+
*/
|
| 134 |
+
selectSlice(state: { [K in ReducerPath]: State }): State
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
/**
|
| 138 |
+
* A slice after being called with `injectInto(reducer)`.
|
| 139 |
+
*
|
| 140 |
+
* Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
|
| 141 |
+
*/
|
| 142 |
+
type InjectedSlice<
|
| 143 |
+
State = any,
|
| 144 |
+
CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
|
| 145 |
+
Name extends string = string,
|
| 146 |
+
ReducerPath extends string = Name,
|
| 147 |
+
Selectors extends SliceSelectors<State> = SliceSelectors<State>,
|
| 148 |
+
> = Omit<
|
| 149 |
+
Slice<State, CaseReducers, Name, ReducerPath, Selectors>,
|
| 150 |
+
'getSelectors' | 'selectors'
|
| 151 |
+
> & {
|
| 152 |
+
/**
|
| 153 |
+
* Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
|
| 154 |
+
*/
|
| 155 |
+
getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>
|
| 156 |
+
|
| 157 |
+
/**
|
| 158 |
+
* Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
|
| 159 |
+
*/
|
| 160 |
+
getSelectors<RootState>(
|
| 161 |
+
selectState: (rootState: RootState) => State | undefined,
|
| 162 |
+
): Id<SliceDefinedSelectors<State, Selectors, RootState>>
|
| 163 |
+
|
| 164 |
+
/**
|
| 165 |
+
* Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
|
| 166 |
+
*
|
| 167 |
+
* Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
|
| 168 |
+
*/
|
| 169 |
+
get selectors(): Id<
|
| 170 |
+
SliceDefinedSelectors<
|
| 171 |
+
State,
|
| 172 |
+
Selectors,
|
| 173 |
+
{ [K in ReducerPath]?: State | undefined }
|
| 174 |
+
>
|
| 175 |
+
>
|
| 176 |
+
|
| 177 |
+
/**
|
| 178 |
+
* Select the slice state, using the slice's current reducerPath.
|
| 179 |
+
*
|
| 180 |
+
* Returns initial state if slice is not found.
|
| 181 |
+
*/
|
| 182 |
+
selectSlice(state: { [K in ReducerPath]?: State | undefined }): State
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
/**
|
| 186 |
+
* Options for `createSlice()`.
|
| 187 |
+
*
|
| 188 |
+
* @public
|
| 189 |
+
*/
|
| 190 |
+
export interface CreateSliceOptions<
|
| 191 |
+
State = any,
|
| 192 |
+
CR extends SliceCaseReducers<State> = SliceCaseReducers<State>,
|
| 193 |
+
Name extends string = string,
|
| 194 |
+
ReducerPath extends string = Name,
|
| 195 |
+
Selectors extends SliceSelectors<State> = SliceSelectors<State>,
|
| 196 |
+
> {
|
| 197 |
+
/**
|
| 198 |
+
* The slice's name. Used to namespace the generated action types.
|
| 199 |
+
*/
|
| 200 |
+
name: Name
|
| 201 |
+
|
| 202 |
+
/**
|
| 203 |
+
* The slice's reducer path. Used when injecting into a combined slice reducer.
|
| 204 |
+
*/
|
| 205 |
+
reducerPath?: ReducerPath
|
| 206 |
+
|
| 207 |
+
/**
|
| 208 |
+
* The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
|
| 209 |
+
*/
|
| 210 |
+
initialState: State | (() => State)
|
| 211 |
+
|
| 212 |
+
/**
|
| 213 |
+
* A mapping from action types to action-type-specific *case reducer*
|
| 214 |
+
* functions. For every action type, a matching action creator will be
|
| 215 |
+
* generated using `createAction()`.
|
| 216 |
+
*/
|
| 217 |
+
reducers:
|
| 218 |
+
| ValidateSliceCaseReducers<State, CR>
|
| 219 |
+
| ((creators: ReducerCreators<State>) => CR)
|
| 220 |
+
|
| 221 |
+
/**
|
| 222 |
+
* A callback that receives a *builder* object to define
|
| 223 |
+
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
|
| 224 |
+
*
|
| 225 |
+
*
|
| 226 |
+
* @example
|
| 227 |
+
* ```ts
|
| 228 |
+
* import type { Action } from '@reduxjs/toolkit';
|
| 229 |
+
* import { createAction, createSlice } from '@reduxjs/toolkit';
|
| 230 |
+
*
|
| 231 |
+
* const incrementBy = createAction<number>('incrementBy');
|
| 232 |
+
* const decrement = createAction('decrement');
|
| 233 |
+
*
|
| 234 |
+
* interface RejectedAction extends Action {
|
| 235 |
+
* error: Error;
|
| 236 |
+
* }
|
| 237 |
+
*
|
| 238 |
+
* function isRejectedAction(action: Action): action is RejectedAction {
|
| 239 |
+
* return action.type.endsWith('rejected');
|
| 240 |
+
* }
|
| 241 |
+
*
|
| 242 |
+
* createSlice({
|
| 243 |
+
* name: 'counter',
|
| 244 |
+
* initialState: 0,
|
| 245 |
+
* reducers: {},
|
| 246 |
+
* extraReducers: (builder) => {
|
| 247 |
+
* builder
|
| 248 |
+
* .addCase(incrementBy, (state, action) => {
|
| 249 |
+
* // action is inferred correctly here if using TS
|
| 250 |
+
* })
|
| 251 |
+
* // You can chain calls, or have separate `builder.addCase()` lines each time
|
| 252 |
+
* .addCase(decrement, (state, action) => {})
|
| 253 |
+
* // You can match a range of action types
|
| 254 |
+
* .addMatcher(
|
| 255 |
+
* isRejectedAction,
|
| 256 |
+
* // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
|
| 257 |
+
* (state, action) => {},
|
| 258 |
+
* )
|
| 259 |
+
* // and provide a default case if no other handlers matched
|
| 260 |
+
* .addDefaultCase((state, action) => {});
|
| 261 |
+
* },
|
| 262 |
+
* });
|
| 263 |
+
* ```
|
| 264 |
+
*/
|
| 265 |
+
extraReducers?: (builder: ActionReducerMapBuilder<State>) => void
|
| 266 |
+
|
| 267 |
+
/**
|
| 268 |
+
* A map of selectors that receive the slice's state and any additional arguments, and return a result.
|
| 269 |
+
*/
|
| 270 |
+
selectors?: Selectors
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
export enum ReducerType {
|
| 274 |
+
reducer = 'reducer',
|
| 275 |
+
reducerWithPrepare = 'reducerWithPrepare',
|
| 276 |
+
asyncThunk = 'asyncThunk',
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
type ReducerDefinition<T extends ReducerType = ReducerType> = {
|
| 280 |
+
_reducerDefinitionType: T
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
export type CaseReducerDefinition<
|
| 284 |
+
S = any,
|
| 285 |
+
A extends Action = UnknownAction,
|
| 286 |
+
> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>
|
| 287 |
+
|
| 288 |
+
/**
|
| 289 |
+
* A CaseReducer with a `prepare` method.
|
| 290 |
+
*
|
| 291 |
+
* @public
|
| 292 |
+
*/
|
| 293 |
+
export type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
|
| 294 |
+
reducer: CaseReducer<State, Action>
|
| 295 |
+
prepare: PrepareAction<Action['payload']>
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
export interface CaseReducerWithPrepareDefinition<
|
| 299 |
+
State,
|
| 300 |
+
Action extends PayloadAction,
|
| 301 |
+
> extends CaseReducerWithPrepare<State, Action>,
|
| 302 |
+
ReducerDefinition<ReducerType.reducerWithPrepare> {}
|
| 303 |
+
|
| 304 |
+
type AsyncThunkSliceReducerConfig<
|
| 305 |
+
State,
|
| 306 |
+
ThunkArg extends any,
|
| 307 |
+
Returned = unknown,
|
| 308 |
+
ThunkApiConfig extends AsyncThunkConfig = {},
|
| 309 |
+
> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
|
| 310 |
+
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
type AsyncThunkSliceReducerDefinition<
|
| 314 |
+
State,
|
| 315 |
+
ThunkArg extends any,
|
| 316 |
+
Returned = unknown,
|
| 317 |
+
ThunkApiConfig extends AsyncThunkConfig = {},
|
| 318 |
+
> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> &
|
| 319 |
+
ReducerDefinition<ReducerType.asyncThunk> & {
|
| 320 |
+
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
/**
|
| 324 |
+
* Providing these as part of the config would cause circular types, so we disallow passing them
|
| 325 |
+
*/
|
| 326 |
+
type PreventCircular<ThunkApiConfig> = {
|
| 327 |
+
[K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch'
|
| 328 |
+
? never
|
| 329 |
+
: ThunkApiConfig[K]
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
interface AsyncThunkCreator<
|
| 333 |
+
State,
|
| 334 |
+
CurriedThunkApiConfig extends
|
| 335 |
+
PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>,
|
| 336 |
+
> {
|
| 337 |
+
<Returned, ThunkArg = void>(
|
| 338 |
+
payloadCreator: AsyncThunkPayloadCreator<
|
| 339 |
+
Returned,
|
| 340 |
+
ThunkArg,
|
| 341 |
+
CurriedThunkApiConfig
|
| 342 |
+
>,
|
| 343 |
+
config?: AsyncThunkSliceReducerConfig<
|
| 344 |
+
State,
|
| 345 |
+
ThunkArg,
|
| 346 |
+
Returned,
|
| 347 |
+
CurriedThunkApiConfig
|
| 348 |
+
>,
|
| 349 |
+
): AsyncThunkSliceReducerDefinition<
|
| 350 |
+
State,
|
| 351 |
+
ThunkArg,
|
| 352 |
+
Returned,
|
| 353 |
+
CurriedThunkApiConfig
|
| 354 |
+
>
|
| 355 |
+
<
|
| 356 |
+
Returned,
|
| 357 |
+
ThunkArg,
|
| 358 |
+
ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {},
|
| 359 |
+
>(
|
| 360 |
+
payloadCreator: AsyncThunkPayloadCreator<
|
| 361 |
+
Returned,
|
| 362 |
+
ThunkArg,
|
| 363 |
+
ThunkApiConfig
|
| 364 |
+
>,
|
| 365 |
+
config?: AsyncThunkSliceReducerConfig<
|
| 366 |
+
State,
|
| 367 |
+
ThunkArg,
|
| 368 |
+
Returned,
|
| 369 |
+
ThunkApiConfig
|
| 370 |
+
>,
|
| 371 |
+
): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>
|
| 372 |
+
withTypes<
|
| 373 |
+
ThunkApiConfig extends PreventCircular<AsyncThunkConfig>,
|
| 374 |
+
>(): AsyncThunkCreator<
|
| 375 |
+
State,
|
| 376 |
+
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>
|
| 377 |
+
>
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
export interface ReducerCreators<State> {
|
| 381 |
+
reducer(
|
| 382 |
+
caseReducer: CaseReducer<State, PayloadAction>,
|
| 383 |
+
): CaseReducerDefinition<State, PayloadAction>
|
| 384 |
+
reducer<Payload>(
|
| 385 |
+
caseReducer: CaseReducer<State, PayloadAction<Payload>>,
|
| 386 |
+
): CaseReducerDefinition<State, PayloadAction<Payload>>
|
| 387 |
+
|
| 388 |
+
asyncThunk: AsyncThunkCreator<State>
|
| 389 |
+
|
| 390 |
+
preparedReducer<Prepare extends PrepareAction<any>>(
|
| 391 |
+
prepare: Prepare,
|
| 392 |
+
reducer: CaseReducer<
|
| 393 |
+
State,
|
| 394 |
+
ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>
|
| 395 |
+
>,
|
| 396 |
+
): {
|
| 397 |
+
_reducerDefinitionType: ReducerType.reducerWithPrepare
|
| 398 |
+
prepare: Prepare
|
| 399 |
+
reducer: CaseReducer<
|
| 400 |
+
State,
|
| 401 |
+
ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>
|
| 402 |
+
>
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
/**
|
| 407 |
+
* The type describing a slice's `reducers` option.
|
| 408 |
+
*
|
| 409 |
+
* @public
|
| 410 |
+
*/
|
| 411 |
+
export type SliceCaseReducers<State> =
|
| 412 |
+
| Record<string, ReducerDefinition>
|
| 413 |
+
| Record<
|
| 414 |
+
string,
|
| 415 |
+
| CaseReducer<State, PayloadAction<any>>
|
| 416 |
+
| CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>
|
| 417 |
+
>
|
| 418 |
+
|
| 419 |
+
/**
|
| 420 |
+
* The type describing a slice's `selectors` option.
|
| 421 |
+
*/
|
| 422 |
+
export type SliceSelectors<State> = {
|
| 423 |
+
[K: string]: (sliceState: State, ...args: any[]) => any
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
type SliceActionType<
|
| 427 |
+
SliceName extends string,
|
| 428 |
+
ActionName extends keyof any,
|
| 429 |
+
> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string
|
| 430 |
+
|
| 431 |
+
/**
|
| 432 |
+
* Derives the slice's `actions` property from the `reducers` options
|
| 433 |
+
*
|
| 434 |
+
* @public
|
| 435 |
+
*/
|
| 436 |
+
export type CaseReducerActions<
|
| 437 |
+
CaseReducers extends SliceCaseReducers<any>,
|
| 438 |
+
SliceName extends string,
|
| 439 |
+
> = {
|
| 440 |
+
[Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition
|
| 441 |
+
? Definition extends { prepare: any }
|
| 442 |
+
? ActionCreatorForCaseReducerWithPrepare<
|
| 443 |
+
Definition,
|
| 444 |
+
SliceActionType<SliceName, Type>
|
| 445 |
+
>
|
| 446 |
+
: Definition extends AsyncThunkSliceReducerDefinition<
|
| 447 |
+
any,
|
| 448 |
+
infer ThunkArg,
|
| 449 |
+
infer Returned,
|
| 450 |
+
infer ThunkApiConfig
|
| 451 |
+
>
|
| 452 |
+
? AsyncThunk<Returned, ThunkArg, ThunkApiConfig>
|
| 453 |
+
: Definition extends { reducer: any }
|
| 454 |
+
? ActionCreatorForCaseReducer<
|
| 455 |
+
Definition['reducer'],
|
| 456 |
+
SliceActionType<SliceName, Type>
|
| 457 |
+
>
|
| 458 |
+
: ActionCreatorForCaseReducer<
|
| 459 |
+
Definition,
|
| 460 |
+
SliceActionType<SliceName, Type>
|
| 461 |
+
>
|
| 462 |
+
: never
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
/**
|
| 466 |
+
* Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
|
| 467 |
+
*
|
| 468 |
+
* @internal
|
| 469 |
+
*/
|
| 470 |
+
type ActionCreatorForCaseReducerWithPrepare<
|
| 471 |
+
CR extends { prepare: any },
|
| 472 |
+
Type extends string,
|
| 473 |
+
> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>
|
| 474 |
+
|
| 475 |
+
/**
|
| 476 |
+
* Get a `PayloadActionCreator` type for a passed `CaseReducer`
|
| 477 |
+
*
|
| 478 |
+
* @internal
|
| 479 |
+
*/
|
| 480 |
+
type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (
|
| 481 |
+
state: any,
|
| 482 |
+
action: infer Action,
|
| 483 |
+
) => any
|
| 484 |
+
? Action extends { payload: infer P }
|
| 485 |
+
? PayloadActionCreator<P, Type>
|
| 486 |
+
: ActionCreatorWithoutPayload<Type>
|
| 487 |
+
: ActionCreatorWithoutPayload<Type>
|
| 488 |
+
|
| 489 |
+
/**
|
| 490 |
+
* Extracts the CaseReducers out of a `reducers` object, even if they are
|
| 491 |
+
* tested into a `CaseReducerWithPrepare`.
|
| 492 |
+
*
|
| 493 |
+
* @internal
|
| 494 |
+
*/
|
| 495 |
+
type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
|
| 496 |
+
[Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition
|
| 497 |
+
? Definition extends AsyncThunkSliceReducerDefinition<any, any, any>
|
| 498 |
+
? Id<
|
| 499 |
+
Pick<
|
| 500 |
+
Required<Definition>,
|
| 501 |
+
'fulfilled' | 'rejected' | 'pending' | 'settled'
|
| 502 |
+
>
|
| 503 |
+
>
|
| 504 |
+
: Definition extends {
|
| 505 |
+
reducer: infer Reducer
|
| 506 |
+
}
|
| 507 |
+
? Reducer
|
| 508 |
+
: Definition
|
| 509 |
+
: never
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
type RemappedSelector<S extends Selector, NewState> =
|
| 513 |
+
S extends Selector<any, infer R, infer P>
|
| 514 |
+
? Selector<NewState, R, P> & { unwrapped: S }
|
| 515 |
+
: never
|
| 516 |
+
|
| 517 |
+
/**
|
| 518 |
+
* Extracts the final selector type from the `selectors` object.
|
| 519 |
+
*
|
| 520 |
+
* Removes the `string` index signature from the default value.
|
| 521 |
+
*/
|
| 522 |
+
type SliceDefinedSelectors<
|
| 523 |
+
State,
|
| 524 |
+
Selectors extends SliceSelectors<State>,
|
| 525 |
+
RootState,
|
| 526 |
+
> = {
|
| 527 |
+
[K in keyof Selectors as string extends K ? never : K]: RemappedSelector<
|
| 528 |
+
Selectors[K],
|
| 529 |
+
RootState
|
| 530 |
+
>
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
/**
|
| 534 |
+
* Used on a SliceCaseReducers object.
|
| 535 |
+
* Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
|
| 536 |
+
* the `reducer` and the `prepare` function use the same type of `payload`.
|
| 537 |
+
*
|
| 538 |
+
* Might do additional such checks in the future.
|
| 539 |
+
*
|
| 540 |
+
* This type is only ever useful if you want to write your own wrapper around
|
| 541 |
+
* `createSlice`. Please don't use it otherwise!
|
| 542 |
+
*
|
| 543 |
+
* @public
|
| 544 |
+
*/
|
| 545 |
+
export type ValidateSliceCaseReducers<
|
| 546 |
+
S,
|
| 547 |
+
ACR extends SliceCaseReducers<S>,
|
| 548 |
+
> = ACR & {
|
| 549 |
+
[T in keyof ACR]: ACR[T] extends {
|
| 550 |
+
reducer(s: S, action?: infer A): any
|
| 551 |
+
}
|
| 552 |
+
? {
|
| 553 |
+
prepare(...a: never[]): Omit<A, 'type'>
|
| 554 |
+
}
|
| 555 |
+
: {}
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
function getType(slice: string, actionKey: string): string {
|
| 559 |
+
return `${slice}/${actionKey}`
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
interface BuildCreateSliceConfig {
|
| 563 |
+
creators?: {
|
| 564 |
+
asyncThunk?: typeof asyncThunkCreator
|
| 565 |
+
}
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
|
| 569 |
+
const cAT = creators?.asyncThunk?.[asyncThunkSymbol]
|
| 570 |
+
return function createSlice<
|
| 571 |
+
State,
|
| 572 |
+
CaseReducers extends SliceCaseReducers<State>,
|
| 573 |
+
Name extends string,
|
| 574 |
+
Selectors extends SliceSelectors<State>,
|
| 575 |
+
ReducerPath extends string = Name,
|
| 576 |
+
>(
|
| 577 |
+
options: CreateSliceOptions<
|
| 578 |
+
State,
|
| 579 |
+
CaseReducers,
|
| 580 |
+
Name,
|
| 581 |
+
ReducerPath,
|
| 582 |
+
Selectors
|
| 583 |
+
>,
|
| 584 |
+
): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {
|
| 585 |
+
const { name, reducerPath = name as unknown as ReducerPath } = options
|
| 586 |
+
if (!name) {
|
| 587 |
+
throw new Error('`name` is a required option for createSlice')
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
if (
|
| 591 |
+
typeof process !== 'undefined' &&
|
| 592 |
+
process.env.NODE_ENV === 'development'
|
| 593 |
+
) {
|
| 594 |
+
if (options.initialState === undefined) {
|
| 595 |
+
console.error(
|
| 596 |
+
'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',
|
| 597 |
+
)
|
| 598 |
+
}
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
const reducers =
|
| 602 |
+
(typeof options.reducers === 'function'
|
| 603 |
+
? options.reducers(buildReducerCreators<State>())
|
| 604 |
+
: options.reducers) || {}
|
| 605 |
+
|
| 606 |
+
const reducerNames = Object.keys(reducers)
|
| 607 |
+
|
| 608 |
+
const context: ReducerHandlingContext<State> = {
|
| 609 |
+
sliceCaseReducersByName: {},
|
| 610 |
+
sliceCaseReducersByType: {},
|
| 611 |
+
actionCreators: {},
|
| 612 |
+
sliceMatchers: [],
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
const contextMethods: ReducerHandlingContextMethods<State> = {
|
| 616 |
+
addCase(
|
| 617 |
+
typeOrActionCreator: string | TypedActionCreator<any>,
|
| 618 |
+
reducer: CaseReducer<State>,
|
| 619 |
+
) {
|
| 620 |
+
const type =
|
| 621 |
+
typeof typeOrActionCreator === 'string'
|
| 622 |
+
? typeOrActionCreator
|
| 623 |
+
: typeOrActionCreator.type
|
| 624 |
+
if (!type) {
|
| 625 |
+
throw new Error(
|
| 626 |
+
'`context.addCase` cannot be called with an empty action type',
|
| 627 |
+
)
|
| 628 |
+
}
|
| 629 |
+
if (type in context.sliceCaseReducersByType) {
|
| 630 |
+
throw new Error(
|
| 631 |
+
'`context.addCase` cannot be called with two reducers for the same action type: ' +
|
| 632 |
+
type,
|
| 633 |
+
)
|
| 634 |
+
}
|
| 635 |
+
context.sliceCaseReducersByType[type] = reducer
|
| 636 |
+
return contextMethods
|
| 637 |
+
},
|
| 638 |
+
addMatcher(matcher, reducer) {
|
| 639 |
+
context.sliceMatchers.push({ matcher, reducer })
|
| 640 |
+
return contextMethods
|
| 641 |
+
},
|
| 642 |
+
exposeAction(name, actionCreator) {
|
| 643 |
+
context.actionCreators[name] = actionCreator
|
| 644 |
+
return contextMethods
|
| 645 |
+
},
|
| 646 |
+
exposeCaseReducer(name, reducer) {
|
| 647 |
+
context.sliceCaseReducersByName[name] = reducer
|
| 648 |
+
return contextMethods
|
| 649 |
+
},
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
reducerNames.forEach((reducerName) => {
|
| 653 |
+
const reducerDefinition = reducers[reducerName]
|
| 654 |
+
const reducerDetails: ReducerDetails = {
|
| 655 |
+
reducerName,
|
| 656 |
+
type: getType(name, reducerName),
|
| 657 |
+
createNotation: typeof options.reducers === 'function',
|
| 658 |
+
}
|
| 659 |
+
if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {
|
| 660 |
+
handleThunkCaseReducerDefinition(
|
| 661 |
+
reducerDetails,
|
| 662 |
+
reducerDefinition,
|
| 663 |
+
contextMethods,
|
| 664 |
+
cAT,
|
| 665 |
+
)
|
| 666 |
+
} else {
|
| 667 |
+
handleNormalReducerDefinition<State>(
|
| 668 |
+
reducerDetails,
|
| 669 |
+
reducerDefinition as any,
|
| 670 |
+
contextMethods,
|
| 671 |
+
)
|
| 672 |
+
}
|
| 673 |
+
})
|
| 674 |
+
|
| 675 |
+
function buildReducer() {
|
| 676 |
+
if (process.env.NODE_ENV !== 'production') {
|
| 677 |
+
if (typeof options.extraReducers === 'object') {
|
| 678 |
+
throw new Error(
|
| 679 |
+
"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice",
|
| 680 |
+
)
|
| 681 |
+
}
|
| 682 |
+
}
|
| 683 |
+
const [
|
| 684 |
+
extraReducers = {},
|
| 685 |
+
actionMatchers = [],
|
| 686 |
+
defaultCaseReducer = undefined,
|
| 687 |
+
] =
|
| 688 |
+
typeof options.extraReducers === 'function'
|
| 689 |
+
? executeReducerBuilderCallback(options.extraReducers)
|
| 690 |
+
: [options.extraReducers]
|
| 691 |
+
|
| 692 |
+
const finalCaseReducers = {
|
| 693 |
+
...extraReducers,
|
| 694 |
+
...context.sliceCaseReducersByType,
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
return createReducer(options.initialState, (builder) => {
|
| 698 |
+
for (let key in finalCaseReducers) {
|
| 699 |
+
builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>)
|
| 700 |
+
}
|
| 701 |
+
for (let sM of context.sliceMatchers) {
|
| 702 |
+
builder.addMatcher(sM.matcher, sM.reducer)
|
| 703 |
+
}
|
| 704 |
+
for (let m of actionMatchers) {
|
| 705 |
+
builder.addMatcher(m.matcher, m.reducer)
|
| 706 |
+
}
|
| 707 |
+
if (defaultCaseReducer) {
|
| 708 |
+
builder.addDefaultCase(defaultCaseReducer)
|
| 709 |
+
}
|
| 710 |
+
})
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
const selectSelf = (state: State) => state
|
| 714 |
+
|
| 715 |
+
const injectedSelectorCache = new Map<
|
| 716 |
+
boolean,
|
| 717 |
+
WeakMap<
|
| 718 |
+
(rootState: any) => State | undefined,
|
| 719 |
+
Record<string, (rootState: any) => any>
|
| 720 |
+
>
|
| 721 |
+
>()
|
| 722 |
+
|
| 723 |
+
const injectedStateCache = new WeakMap<(rootState: any) => State, State>()
|
| 724 |
+
|
| 725 |
+
let _reducer: ReducerWithInitialState<State>
|
| 726 |
+
|
| 727 |
+
function reducer(state: State | undefined, action: UnknownAction) {
|
| 728 |
+
if (!_reducer) _reducer = buildReducer()
|
| 729 |
+
|
| 730 |
+
return _reducer(state, action)
|
| 731 |
+
}
|
| 732 |
+
|
| 733 |
+
function getInitialState() {
|
| 734 |
+
if (!_reducer) _reducer = buildReducer()
|
| 735 |
+
|
| 736 |
+
return _reducer.getInitialState()
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(
|
| 740 |
+
reducerPath: CurrentReducerPath,
|
| 741 |
+
injected = false,
|
| 742 |
+
): Pick<
|
| 743 |
+
Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>,
|
| 744 |
+
'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'
|
| 745 |
+
> {
|
| 746 |
+
function selectSlice(state: { [K in CurrentReducerPath]: State }) {
|
| 747 |
+
let sliceState = state[reducerPath]
|
| 748 |
+
if (typeof sliceState === 'undefined') {
|
| 749 |
+
if (injected) {
|
| 750 |
+
sliceState = getOrInsertComputed(
|
| 751 |
+
injectedStateCache,
|
| 752 |
+
selectSlice,
|
| 753 |
+
getInitialState,
|
| 754 |
+
)
|
| 755 |
+
} else if (process.env.NODE_ENV !== 'production') {
|
| 756 |
+
throw new Error(
|
| 757 |
+
'selectSlice returned undefined for an uninjected slice reducer',
|
| 758 |
+
)
|
| 759 |
+
}
|
| 760 |
+
}
|
| 761 |
+
return sliceState
|
| 762 |
+
}
|
| 763 |
+
|
| 764 |
+
function getSelectors(
|
| 765 |
+
selectState: (rootState: any) => State = selectSelf,
|
| 766 |
+
) {
|
| 767 |
+
const selectorCache = getOrInsertComputed(
|
| 768 |
+
injectedSelectorCache,
|
| 769 |
+
injected,
|
| 770 |
+
() => new WeakMap(),
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
return getOrInsertComputed(selectorCache, selectState, () => {
|
| 774 |
+
const map: Record<string, Selector<any, any>> = {}
|
| 775 |
+
for (const [name, selector] of Object.entries(
|
| 776 |
+
options.selectors ?? {},
|
| 777 |
+
)) {
|
| 778 |
+
map[name] = wrapSelector(
|
| 779 |
+
selector,
|
| 780 |
+
selectState,
|
| 781 |
+
() =>
|
| 782 |
+
getOrInsertComputed(
|
| 783 |
+
injectedStateCache,
|
| 784 |
+
selectState,
|
| 785 |
+
getInitialState,
|
| 786 |
+
),
|
| 787 |
+
injected,
|
| 788 |
+
)
|
| 789 |
+
}
|
| 790 |
+
return map
|
| 791 |
+
}) as any
|
| 792 |
+
}
|
| 793 |
+
return {
|
| 794 |
+
reducerPath,
|
| 795 |
+
getSelectors,
|
| 796 |
+
get selectors() {
|
| 797 |
+
return getSelectors(selectSlice)
|
| 798 |
+
},
|
| 799 |
+
selectSlice,
|
| 800 |
+
}
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {
|
| 804 |
+
name,
|
| 805 |
+
reducer,
|
| 806 |
+
actions: context.actionCreators as any,
|
| 807 |
+
caseReducers: context.sliceCaseReducersByName as any,
|
| 808 |
+
getInitialState,
|
| 809 |
+
...makeSelectorProps(reducerPath),
|
| 810 |
+
injectInto(injectable, { reducerPath: pathOpt, ...config } = {}) {
|
| 811 |
+
const newReducerPath = pathOpt ?? reducerPath
|
| 812 |
+
injectable.inject({ reducerPath: newReducerPath, reducer }, config)
|
| 813 |
+
return {
|
| 814 |
+
...slice,
|
| 815 |
+
...makeSelectorProps(newReducerPath, true),
|
| 816 |
+
} as any
|
| 817 |
+
},
|
| 818 |
+
}
|
| 819 |
+
return slice
|
| 820 |
+
}
|
| 821 |
+
}
|
| 822 |
+
|
| 823 |
+
function wrapSelector<State, NewState, S extends Selector<State>>(
|
| 824 |
+
selector: S,
|
| 825 |
+
selectState: Selector<NewState, State>,
|
| 826 |
+
getInitialState: () => State,
|
| 827 |
+
injected?: boolean,
|
| 828 |
+
) {
|
| 829 |
+
function wrapper(rootState: NewState, ...args: any[]) {
|
| 830 |
+
let sliceState = selectState(rootState)
|
| 831 |
+
if (typeof sliceState === 'undefined') {
|
| 832 |
+
if (injected) {
|
| 833 |
+
sliceState = getInitialState()
|
| 834 |
+
} else if (process.env.NODE_ENV !== 'production') {
|
| 835 |
+
throw new Error(
|
| 836 |
+
'selectState returned undefined for an uninjected slice reducer',
|
| 837 |
+
)
|
| 838 |
+
}
|
| 839 |
+
}
|
| 840 |
+
return selector(sliceState, ...args)
|
| 841 |
+
}
|
| 842 |
+
wrapper.unwrapped = selector
|
| 843 |
+
return wrapper as RemappedSelector<S, NewState>
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
/**
|
| 847 |
+
* A function that accepts an initial state, an object full of reducer
|
| 848 |
+
* functions, and a "slice name", and automatically generates
|
| 849 |
+
* action creators and action types that correspond to the
|
| 850 |
+
* reducers and state.
|
| 851 |
+
*
|
| 852 |
+
* @public
|
| 853 |
+
*/
|
| 854 |
+
export const createSlice = /* @__PURE__ */ buildCreateSlice()
|
| 855 |
+
|
| 856 |
+
interface ReducerHandlingContext<State> {
|
| 857 |
+
sliceCaseReducersByName: Record<
|
| 858 |
+
string,
|
| 859 |
+
| CaseReducer<State, any>
|
| 860 |
+
| Pick<
|
| 861 |
+
AsyncThunkSliceReducerDefinition<State, any, any, any>,
|
| 862 |
+
'fulfilled' | 'rejected' | 'pending' | 'settled'
|
| 863 |
+
>
|
| 864 |
+
>
|
| 865 |
+
sliceCaseReducersByType: Record<string, CaseReducer<State, any>>
|
| 866 |
+
sliceMatchers: ActionMatcherDescriptionCollection<State>
|
| 867 |
+
actionCreators: Record<string, Function>
|
| 868 |
+
}
|
| 869 |
+
|
| 870 |
+
interface ReducerHandlingContextMethods<State> {
|
| 871 |
+
/**
|
| 872 |
+
* Adds a case reducer to handle a single action type.
|
| 873 |
+
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
|
| 874 |
+
* @param reducer - The actual case reducer function.
|
| 875 |
+
*/
|
| 876 |
+
addCase<ActionCreator extends TypedActionCreator<string>>(
|
| 877 |
+
actionCreator: ActionCreator,
|
| 878 |
+
reducer: CaseReducer<State, ReturnType<ActionCreator>>,
|
| 879 |
+
): ReducerHandlingContextMethods<State>
|
| 880 |
+
/**
|
| 881 |
+
* Adds a case reducer to handle a single action type.
|
| 882 |
+
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
|
| 883 |
+
* @param reducer - The actual case reducer function.
|
| 884 |
+
*/
|
| 885 |
+
addCase<Type extends string, A extends Action<Type>>(
|
| 886 |
+
type: Type,
|
| 887 |
+
reducer: CaseReducer<State, A>,
|
| 888 |
+
): ReducerHandlingContextMethods<State>
|
| 889 |
+
|
| 890 |
+
/**
|
| 891 |
+
* Allows you to match incoming actions against your own filter function instead of only the `action.type` property.
|
| 892 |
+
* @remarks
|
| 893 |
+
* If multiple matcher reducers match, all of them will be executed in the order
|
| 894 |
+
* they were defined in - even if a case reducer already matched.
|
| 895 |
+
* All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.
|
| 896 |
+
* @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
|
| 897 |
+
* function
|
| 898 |
+
* @param reducer - The actual case reducer function.
|
| 899 |
+
*
|
| 900 |
+
*/
|
| 901 |
+
addMatcher<A>(
|
| 902 |
+
matcher: TypeGuard<A>,
|
| 903 |
+
reducer: CaseReducer<State, A extends Action ? A : A & Action>,
|
| 904 |
+
): ReducerHandlingContextMethods<State>
|
| 905 |
+
/**
|
| 906 |
+
* Add an action to be exposed under the final `slice.actions` key.
|
| 907 |
+
* @param name The key to be exposed as.
|
| 908 |
+
* @param actionCreator The action to expose.
|
| 909 |
+
* @example
|
| 910 |
+
* ```ts
|
| 911 |
+
* context.exposeAction('addPost', createAction<Post>('addPost'));
|
| 912 |
+
*
|
| 913 |
+
* export const { addPost } = slice.actions;
|
| 914 |
+
*
|
| 915 |
+
* dispatch(addPost(post));
|
| 916 |
+
* ```
|
| 917 |
+
*/
|
| 918 |
+
exposeAction(
|
| 919 |
+
name: string,
|
| 920 |
+
actionCreator: Function,
|
| 921 |
+
): ReducerHandlingContextMethods<State>
|
| 922 |
+
/**
|
| 923 |
+
* Add a case reducer to be exposed under the final `slice.caseReducers` key.
|
| 924 |
+
* @param name The key to be exposed as.
|
| 925 |
+
* @param reducer The reducer to expose.
|
| 926 |
+
* @example
|
| 927 |
+
* ```ts
|
| 928 |
+
* context.exposeCaseReducer('addPost', (state, action: PayloadAction<Post>) => {
|
| 929 |
+
* state.push(action.payload);
|
| 930 |
+
* });
|
| 931 |
+
*
|
| 932 |
+
* slice.caseReducers.addPost([], addPost(post));
|
| 933 |
+
* ```
|
| 934 |
+
*/
|
| 935 |
+
exposeCaseReducer(
|
| 936 |
+
name: string,
|
| 937 |
+
reducer:
|
| 938 |
+
| CaseReducer<State, any>
|
| 939 |
+
| Pick<
|
| 940 |
+
AsyncThunkSliceReducerDefinition<State, any, any, any>,
|
| 941 |
+
'fulfilled' | 'rejected' | 'pending' | 'settled'
|
| 942 |
+
>,
|
| 943 |
+
): ReducerHandlingContextMethods<State>
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
interface ReducerDetails {
|
| 947 |
+
/** The key the reducer was defined under */
|
| 948 |
+
reducerName: string
|
| 949 |
+
/** The predefined action type, i.e. `${slice.name}/${reducerName}` */
|
| 950 |
+
type: string
|
| 951 |
+
/** Whether create. notation was used when defining reducers */
|
| 952 |
+
createNotation: boolean
|
| 953 |
+
}
|
| 954 |
+
|
| 955 |
+
function buildReducerCreators<State>(): ReducerCreators<State> {
|
| 956 |
+
function asyncThunk(
|
| 957 |
+
payloadCreator: AsyncThunkPayloadCreator<any, any>,
|
| 958 |
+
config: AsyncThunkSliceReducerConfig<State, any>,
|
| 959 |
+
): AsyncThunkSliceReducerDefinition<State, any> {
|
| 960 |
+
return {
|
| 961 |
+
_reducerDefinitionType: ReducerType.asyncThunk,
|
| 962 |
+
payloadCreator,
|
| 963 |
+
...config,
|
| 964 |
+
}
|
| 965 |
+
}
|
| 966 |
+
asyncThunk.withTypes = () => asyncThunk
|
| 967 |
+
return {
|
| 968 |
+
reducer(caseReducer: CaseReducer<State, any>) {
|
| 969 |
+
return Object.assign(
|
| 970 |
+
{
|
| 971 |
+
// hack so the wrapping function has the same name as the original
|
| 972 |
+
// we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original
|
| 973 |
+
[caseReducer.name](...args: Parameters<typeof caseReducer>) {
|
| 974 |
+
return caseReducer(...args)
|
| 975 |
+
},
|
| 976 |
+
}[caseReducer.name],
|
| 977 |
+
{
|
| 978 |
+
_reducerDefinitionType: ReducerType.reducer,
|
| 979 |
+
} as const,
|
| 980 |
+
)
|
| 981 |
+
},
|
| 982 |
+
preparedReducer(prepare, reducer) {
|
| 983 |
+
return {
|
| 984 |
+
_reducerDefinitionType: ReducerType.reducerWithPrepare,
|
| 985 |
+
prepare,
|
| 986 |
+
reducer,
|
| 987 |
+
}
|
| 988 |
+
},
|
| 989 |
+
asyncThunk: asyncThunk as any,
|
| 990 |
+
}
|
| 991 |
+
}
|
| 992 |
+
|
| 993 |
+
function handleNormalReducerDefinition<State>(
|
| 994 |
+
{ type, reducerName, createNotation }: ReducerDetails,
|
| 995 |
+
maybeReducerWithPrepare:
|
| 996 |
+
| CaseReducer<State, { payload: any; type: string }>
|
| 997 |
+
| CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>,
|
| 998 |
+
context: ReducerHandlingContextMethods<State>,
|
| 999 |
+
) {
|
| 1000 |
+
let caseReducer: CaseReducer<State, any>
|
| 1001 |
+
let prepareCallback: PrepareAction<any> | undefined
|
| 1002 |
+
if ('reducer' in maybeReducerWithPrepare) {
|
| 1003 |
+
if (
|
| 1004 |
+
createNotation &&
|
| 1005 |
+
!isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)
|
| 1006 |
+
) {
|
| 1007 |
+
throw new Error(
|
| 1008 |
+
'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.',
|
| 1009 |
+
)
|
| 1010 |
+
}
|
| 1011 |
+
caseReducer = maybeReducerWithPrepare.reducer
|
| 1012 |
+
prepareCallback = maybeReducerWithPrepare.prepare
|
| 1013 |
+
} else {
|
| 1014 |
+
caseReducer = maybeReducerWithPrepare
|
| 1015 |
+
}
|
| 1016 |
+
context
|
| 1017 |
+
.addCase(type, caseReducer)
|
| 1018 |
+
.exposeCaseReducer(reducerName, caseReducer)
|
| 1019 |
+
.exposeAction(
|
| 1020 |
+
reducerName,
|
| 1021 |
+
prepareCallback
|
| 1022 |
+
? createAction(type, prepareCallback)
|
| 1023 |
+
: createAction(type),
|
| 1024 |
+
)
|
| 1025 |
+
}
|
| 1026 |
+
|
| 1027 |
+
function isAsyncThunkSliceReducerDefinition<State>(
|
| 1028 |
+
reducerDefinition: any,
|
| 1029 |
+
): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {
|
| 1030 |
+
return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk
|
| 1031 |
+
}
|
| 1032 |
+
|
| 1033 |
+
function isCaseReducerWithPrepareDefinition<State>(
|
| 1034 |
+
reducerDefinition: any,
|
| 1035 |
+
): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {
|
| 1036 |
+
return (
|
| 1037 |
+
reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare
|
| 1038 |
+
)
|
| 1039 |
+
}
|
| 1040 |
+
|
| 1041 |
+
function handleThunkCaseReducerDefinition<State>(
|
| 1042 |
+
{ type, reducerName }: ReducerDetails,
|
| 1043 |
+
reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>,
|
| 1044 |
+
context: ReducerHandlingContextMethods<State>,
|
| 1045 |
+
cAT: typeof _createAsyncThunk | undefined,
|
| 1046 |
+
) {
|
| 1047 |
+
if (!cAT) {
|
| 1048 |
+
throw new Error(
|
| 1049 |
+
'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' +
|
| 1050 |
+
'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.',
|
| 1051 |
+
)
|
| 1052 |
+
}
|
| 1053 |
+
const { payloadCreator, fulfilled, pending, rejected, settled, options } =
|
| 1054 |
+
reducerDefinition
|
| 1055 |
+
const thunk = cAT(type, payloadCreator, options as any)
|
| 1056 |
+
context.exposeAction(reducerName, thunk)
|
| 1057 |
+
|
| 1058 |
+
if (fulfilled) {
|
| 1059 |
+
context.addCase(thunk.fulfilled, fulfilled)
|
| 1060 |
+
}
|
| 1061 |
+
if (pending) {
|
| 1062 |
+
context.addCase(thunk.pending, pending)
|
| 1063 |
+
}
|
| 1064 |
+
if (rejected) {
|
| 1065 |
+
context.addCase(thunk.rejected, rejected)
|
| 1066 |
+
}
|
| 1067 |
+
if (settled) {
|
| 1068 |
+
context.addMatcher(thunk.settled, settled)
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
context.exposeCaseReducer(reducerName, {
|
| 1072 |
+
fulfilled: fulfilled || noop,
|
| 1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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Action, ActionCreator, StoreEnhancer } from 'redux'
|
| 2 |
+
import { compose } from './reduxImports'
|
| 3 |
+
|
| 4 |
+
/**
|
| 5 |
+
* @public
|
| 6 |
+
*/
|
| 7 |
+
export interface DevToolsEnhancerOptions {
|
| 8 |
+
/**
|
| 9 |
+
* the instance name to be showed on the monitor page. Default value is `document.title`.
|
| 10 |
+
* If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
|
| 11 |
+
*/
|
| 12 |
+
name?: string
|
| 13 |
+
/**
|
| 14 |
+
* action creators functions to be available in the Dispatcher.
|
| 15 |
+
*/
|
| 16 |
+
actionCreators?: ActionCreator<any>[] | { [key: string]: ActionCreator<any> }
|
| 17 |
+
/**
|
| 18 |
+
* if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
|
| 19 |
+
* It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
|
| 20 |
+
* Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
|
| 21 |
+
*
|
| 22 |
+
* @default 500 ms.
|
| 23 |
+
*/
|
| 24 |
+
latency?: number
|
| 25 |
+
/**
|
| 26 |
+
* (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
|
| 27 |
+
*
|
| 28 |
+
* @default 50
|
| 29 |
+
*/
|
| 30 |
+
maxAge?: number
|
| 31 |
+
/**
|
| 32 |
+
* Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
|
| 33 |
+
* were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
|
| 34 |
+
* functions.
|
| 35 |
+
*/
|
| 36 |
+
serialize?:
|
| 37 |
+
| boolean
|
| 38 |
+
| {
|
| 39 |
+
/**
|
| 40 |
+
* - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
|
| 41 |
+
* - `false` - will handle also circular references.
|
| 42 |
+
* - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
|
| 43 |
+
* - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
|
| 44 |
+
* For each of them you can indicate if to include (by setting as `true`).
|
| 45 |
+
* For `function` key you can also specify a custom function which handles serialization.
|
| 46 |
+
* See [`jsan`](https://github.com/kolodny/jsan) for more details.
|
| 47 |
+
*/
|
| 48 |
+
options?:
|
| 49 |
+
| undefined
|
| 50 |
+
| boolean
|
| 51 |
+
| {
|
| 52 |
+
date?: true
|
| 53 |
+
regex?: true
|
| 54 |
+
undefined?: true
|
| 55 |
+
error?: true
|
| 56 |
+
symbol?: true
|
| 57 |
+
map?: true
|
| 58 |
+
set?: true
|
| 59 |
+
function?: true | ((fn: (...args: any[]) => any) => string)
|
| 60 |
+
}
|
| 61 |
+
/**
|
| 62 |
+
* [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
|
| 63 |
+
* In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
|
| 64 |
+
* key. So you can deserialize it back while importing or persisting data.
|
| 65 |
+
* Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
|
| 66 |
+
*/
|
| 67 |
+
replacer?: (key: string, value: unknown) => any
|
| 68 |
+
/**
|
| 69 |
+
* [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
|
| 70 |
+
* used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
|
| 71 |
+
* as an example on how to serialize special data types and get them back.
|
| 72 |
+
*/
|
| 73 |
+
reviver?: (key: string, value: unknown) => any
|
| 74 |
+
/**
|
| 75 |
+
* Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
|
| 76 |
+
* Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
|
| 77 |
+
* The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
|
| 78 |
+
*/
|
| 79 |
+
immutable?: any
|
| 80 |
+
/**
|
| 81 |
+
* ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
|
| 82 |
+
*/
|
| 83 |
+
refs?: any
|
| 84 |
+
}
|
| 85 |
+
/**
|
| 86 |
+
* function which takes `action` object and id number as arguments, and should return `action` object back.
|
| 87 |
+
*/
|
| 88 |
+
actionSanitizer?: <A extends Action>(action: A, id: number) => A
|
| 89 |
+
/**
|
| 90 |
+
* function which takes `state` object and index as arguments, and should return `state` object back.
|
| 91 |
+
*/
|
| 92 |
+
stateSanitizer?: <S>(state: S, index: number) => S
|
| 93 |
+
/**
|
| 94 |
+
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
|
| 95 |
+
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
|
| 96 |
+
*/
|
| 97 |
+
actionsDenylist?: string | string[]
|
| 98 |
+
/**
|
| 99 |
+
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
|
| 100 |
+
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
|
| 101 |
+
*/
|
| 102 |
+
actionsAllowlist?: string | string[]
|
| 103 |
+
/**
|
| 104 |
+
* called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
|
| 105 |
+
* Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
|
| 106 |
+
*/
|
| 107 |
+
predicate?: <S, A extends Action>(state: S, action: A) => boolean
|
| 108 |
+
/**
|
| 109 |
+
* if specified as `false`, it will not record the changes till clicking on `Start recording` button.
|
| 110 |
+
* Available only for Redux enhancer, for others use `autoPause`.
|
| 111 |
+
*
|
| 112 |
+
* @default true
|
| 113 |
+
*/
|
| 114 |
+
shouldRecordChanges?: boolean
|
| 115 |
+
/**
|
| 116 |
+
* if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
|
| 117 |
+
* If not specified, will commit when paused. Available only for Redux enhancer.
|
| 118 |
+
*
|
| 119 |
+
* @default "@@PAUSED""
|
| 120 |
+
*/
|
| 121 |
+
pauseActionType?: string
|
| 122 |
+
/**
|
| 123 |
+
* auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
|
| 124 |
+
* Not available for Redux enhancer (as it already does it but storing the data to be sent).
|
| 125 |
+
*
|
| 126 |
+
* @default false
|
| 127 |
+
*/
|
| 128 |
+
autoPause?: boolean
|
| 129 |
+
/**
|
| 130 |
+
* if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
|
| 131 |
+
* Available only for Redux enhancer.
|
| 132 |
+
*
|
| 133 |
+
* @default false
|
| 134 |
+
*/
|
| 135 |
+
shouldStartLocked?: boolean
|
| 136 |
+
/**
|
| 137 |
+
* if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
|
| 138 |
+
*
|
| 139 |
+
* @default true
|
| 140 |
+
*/
|
| 141 |
+
shouldHotReload?: boolean
|
| 142 |
+
/**
|
| 143 |
+
* if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
|
| 144 |
+
*
|
| 145 |
+
* @default false
|
| 146 |
+
*/
|
| 147 |
+
shouldCatchErrors?: boolean
|
| 148 |
+
/**
|
| 149 |
+
* If you want to restrict the extension, specify the features you allow.
|
| 150 |
+
* If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
|
| 151 |
+
* Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
|
| 152 |
+
* Otherwise, you'll get/set the data right from the monitor part.
|
| 153 |
+
*/
|
| 154 |
+
features?: {
|
| 155 |
+
/**
|
| 156 |
+
* start/pause recording of dispatched actions
|
| 157 |
+
*/
|
| 158 |
+
pause?: boolean
|
| 159 |
+
/**
|
| 160 |
+
* lock/unlock dispatching actions and side effects
|
| 161 |
+
*/
|
| 162 |
+
lock?: boolean
|
| 163 |
+
/**
|
| 164 |
+
* persist states on page reloading
|
| 165 |
+
*/
|
| 166 |
+
persist?: boolean
|
| 167 |
+
/**
|
| 168 |
+
* export history of actions in a file
|
| 169 |
+
*/
|
| 170 |
+
export?: boolean | 'custom'
|
| 171 |
+
/**
|
| 172 |
+
* import history of actions from a file
|
| 173 |
+
*/
|
| 174 |
+
import?: boolean | 'custom'
|
| 175 |
+
/**
|
| 176 |
+
* jump back and forth (time traveling)
|
| 177 |
+
*/
|
| 178 |
+
jump?: boolean
|
| 179 |
+
/**
|
| 180 |
+
* skip (cancel) actions
|
| 181 |
+
*/
|
| 182 |
+
skip?: boolean
|
| 183 |
+
/**
|
| 184 |
+
* drag and drop actions in the history list
|
| 185 |
+
*/
|
| 186 |
+
reorder?: boolean
|
| 187 |
+
/**
|
| 188 |
+
* dispatch custom actions or action creators
|
| 189 |
+
*/
|
| 190 |
+
dispatch?: boolean
|
| 191 |
+
/**
|
| 192 |
+
* generate tests for the selected actions
|
| 193 |
+
*/
|
| 194 |
+
test?: boolean
|
| 195 |
+
}
|
| 196 |
+
/**
|
| 197 |
+
* Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
|
| 198 |
+
* Defaults to false.
|
| 199 |
+
*/
|
| 200 |
+
trace?: boolean | (<A extends Action>(action: A) => string)
|
| 201 |
+
/**
|
| 202 |
+
* The maximum number of stack trace entries to record per action. Defaults to 10.
|
| 203 |
+
*/
|
| 204 |
+
traceLimit?: number
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
type Compose = typeof compose
|
| 208 |
+
|
| 209 |
+
interface ComposeWithDevTools {
|
| 210 |
+
(options: DevToolsEnhancerOptions): Compose
|
| 211 |
+
<StoreExt extends {}>(
|
| 212 |
+
...funcs: StoreEnhancer<StoreExt>[]
|
| 213 |
+
): StoreEnhancer<StoreExt>
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
/**
|
| 217 |
+
* @public
|
| 218 |
+
*/
|
| 219 |
+
export const composeWithDevTools: ComposeWithDevTools =
|
| 220 |
+
typeof window !== 'undefined' &&
|
| 221 |
+
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
|
| 222 |
+
? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
|
| 223 |
+
: function () {
|
| 224 |
+
if (arguments.length === 0) return undefined
|
| 225 |
+
if (typeof arguments[0] === 'object') return compose
|
| 226 |
+
return compose.apply(null, arguments as any as Function[])
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/**
|
| 230 |
+
* @public
|
| 231 |
+
*/
|
| 232 |
+
export const devToolsEnhancer: {
|
| 233 |
+
(options: DevToolsEnhancerOptions): StoreEnhancer<any>
|
| 234 |
+
} =
|
| 235 |
+
typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__
|
| 236 |
+
? (window as any).__REDUX_DEVTOOLS_EXTENSION__
|
| 237 |
+
: function () {
|
| 238 |
+
return function (noop) {
|
| 239 |
+
return noop
|
| 240 |
+
}
|
| 241 |
+
}
|
node_modules/@reduxjs/toolkit/src/dynamicMiddleware/index.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Dispatch, Middleware, UnknownAction } from 'redux'
|
| 2 |
+
import { compose } from '../reduxImports'
|
| 3 |
+
import { createAction } from '../createAction'
|
| 4 |
+
import { isAllOf } from '../matchers'
|
| 5 |
+
import { nanoid } from '../nanoid'
|
| 6 |
+
import { getOrInsertComputed } from '../utils'
|
| 7 |
+
import type {
|
| 8 |
+
AddMiddleware,
|
| 9 |
+
DynamicMiddleware,
|
| 10 |
+
DynamicMiddlewareInstance,
|
| 11 |
+
MiddlewareEntry,
|
| 12 |
+
WithMiddleware,
|
| 13 |
+
} from './types'
|
| 14 |
+
export type {
|
| 15 |
+
DynamicMiddlewareInstance,
|
| 16 |
+
GetDispatchType as GetDispatch,
|
| 17 |
+
MiddlewareApiConfig,
|
| 18 |
+
} from './types'
|
| 19 |
+
|
| 20 |
+
const createMiddlewareEntry = <
|
| 21 |
+
State = any,
|
| 22 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 23 |
+
>(
|
| 24 |
+
middleware: Middleware<any, State, DispatchType>,
|
| 25 |
+
): MiddlewareEntry<State, DispatchType> => ({
|
| 26 |
+
middleware,
|
| 27 |
+
applied: new Map(),
|
| 28 |
+
})
|
| 29 |
+
|
| 30 |
+
const matchInstance =
|
| 31 |
+
(instanceId: string) =>
|
| 32 |
+
(action: any): action is { meta: { instanceId: string } } =>
|
| 33 |
+
action?.meta?.instanceId === instanceId
|
| 34 |
+
|
| 35 |
+
export const createDynamicMiddleware = <
|
| 36 |
+
State = any,
|
| 37 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 38 |
+
>(): DynamicMiddlewareInstance<State, DispatchType> => {
|
| 39 |
+
const instanceId = nanoid()
|
| 40 |
+
const middlewareMap = new Map<
|
| 41 |
+
Middleware<any, State, DispatchType>,
|
| 42 |
+
MiddlewareEntry<State, DispatchType>
|
| 43 |
+
>()
|
| 44 |
+
|
| 45 |
+
const withMiddleware = Object.assign(
|
| 46 |
+
createAction(
|
| 47 |
+
'dynamicMiddleware/add',
|
| 48 |
+
(...middlewares: Middleware<any, State, DispatchType>[]) => ({
|
| 49 |
+
payload: middlewares,
|
| 50 |
+
meta: {
|
| 51 |
+
instanceId,
|
| 52 |
+
},
|
| 53 |
+
}),
|
| 54 |
+
),
|
| 55 |
+
{ withTypes: () => withMiddleware },
|
| 56 |
+
) as WithMiddleware<State, DispatchType>
|
| 57 |
+
|
| 58 |
+
const addMiddleware = Object.assign(
|
| 59 |
+
function addMiddleware(
|
| 60 |
+
...middlewares: Middleware<any, State, DispatchType>[]
|
| 61 |
+
) {
|
| 62 |
+
middlewares.forEach((middleware) => {
|
| 63 |
+
getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)
|
| 64 |
+
})
|
| 65 |
+
},
|
| 66 |
+
{ withTypes: () => addMiddleware },
|
| 67 |
+
) as AddMiddleware<State, DispatchType>
|
| 68 |
+
|
| 69 |
+
const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {
|
| 70 |
+
const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>
|
| 71 |
+
getOrInsertComputed(entry.applied, api, entry.middleware),
|
| 72 |
+
)
|
| 73 |
+
return compose(...appliedMiddleware)
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId))
|
| 77 |
+
|
| 78 |
+
const middleware: DynamicMiddleware<State, DispatchType> =
|
| 79 |
+
(api) => (next) => (action) => {
|
| 80 |
+
if (isWithMiddleware(action)) {
|
| 81 |
+
addMiddleware(...action.payload)
|
| 82 |
+
return api.dispatch
|
| 83 |
+
}
|
| 84 |
+
return getFinalMiddleware(api)(next)(action)
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
middleware,
|
| 89 |
+
addMiddleware,
|
| 90 |
+
withMiddleware,
|
| 91 |
+
instanceId,
|
| 92 |
+
}
|
| 93 |
+
}
|
node_modules/@reduxjs/toolkit/src/dynamicMiddleware/react/index.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {
|
| 2 |
+
DynamicMiddlewareInstance,
|
| 3 |
+
GetDispatch,
|
| 4 |
+
GetState,
|
| 5 |
+
MiddlewareApiConfig,
|
| 6 |
+
TSHelpersExtractDispatchExtensions,
|
| 7 |
+
} from '@reduxjs/toolkit'
|
| 8 |
+
import { createDynamicMiddleware as cDM } from '@reduxjs/toolkit'
|
| 9 |
+
import type { Context } from 'react'
|
| 10 |
+
import type { ReactReduxContextValue } from 'react-redux'
|
| 11 |
+
import {
|
| 12 |
+
createDispatchHook,
|
| 13 |
+
ReactReduxContext,
|
| 14 |
+
useDispatch as useDefaultDispatch,
|
| 15 |
+
} from 'react-redux'
|
| 16 |
+
import type { Action, Dispatch, Middleware, UnknownAction } from 'redux'
|
| 17 |
+
|
| 18 |
+
export type UseDispatchWithMiddlewareHook<
|
| 19 |
+
Middlewares extends Middleware<any, State, DispatchType>[] = [],
|
| 20 |
+
State = any,
|
| 21 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 22 |
+
> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType
|
| 23 |
+
|
| 24 |
+
export type CreateDispatchWithMiddlewareHook<
|
| 25 |
+
State = any,
|
| 26 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 27 |
+
> = {
|
| 28 |
+
<
|
| 29 |
+
Middlewares extends [
|
| 30 |
+
Middleware<any, State, DispatchType>,
|
| 31 |
+
...Middleware<any, State, DispatchType>[],
|
| 32 |
+
],
|
| 33 |
+
>(
|
| 34 |
+
...middlewares: Middlewares
|
| 35 |
+
): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>
|
| 36 |
+
withTypes<
|
| 37 |
+
MiddlewareConfig extends MiddlewareApiConfig,
|
| 38 |
+
>(): CreateDispatchWithMiddlewareHook<
|
| 39 |
+
GetState<MiddlewareConfig>,
|
| 40 |
+
GetDispatch<MiddlewareConfig>
|
| 41 |
+
>
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
type ActionFromDispatch<DispatchType extends Dispatch<Action>> =
|
| 45 |
+
DispatchType extends Dispatch<infer Action> ? Action : never
|
| 46 |
+
|
| 47 |
+
type ReactDynamicMiddlewareInstance<
|
| 48 |
+
State = any,
|
| 49 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 50 |
+
> = DynamicMiddlewareInstance<State, DispatchType> & {
|
| 51 |
+
createDispatchWithMiddlewareHookFactory: (
|
| 52 |
+
context?: Context<ReactReduxContextValue<
|
| 53 |
+
State,
|
| 54 |
+
ActionFromDispatch<DispatchType>
|
| 55 |
+
> | null>,
|
| 56 |
+
) => CreateDispatchWithMiddlewareHook<State, DispatchType>
|
| 57 |
+
createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<
|
| 58 |
+
State,
|
| 59 |
+
DispatchType
|
| 60 |
+
>
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
export const createDynamicMiddleware = <
|
| 64 |
+
State = any,
|
| 65 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 66 |
+
>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {
|
| 67 |
+
const instance = cDM<State, DispatchType>()
|
| 68 |
+
const createDispatchWithMiddlewareHookFactory = (
|
| 69 |
+
// @ts-ignore
|
| 70 |
+
context: Context<ReactReduxContextValue<
|
| 71 |
+
State,
|
| 72 |
+
ActionFromDispatch<DispatchType>
|
| 73 |
+
> | null> = ReactReduxContext,
|
| 74 |
+
) => {
|
| 75 |
+
const useDispatch =
|
| 76 |
+
context === ReactReduxContext
|
| 77 |
+
? useDefaultDispatch
|
| 78 |
+
: createDispatchHook(context)
|
| 79 |
+
function createDispatchWithMiddlewareHook<
|
| 80 |
+
Middlewares extends Middleware<any, State, DispatchType>[],
|
| 81 |
+
>(...middlewares: Middlewares) {
|
| 82 |
+
instance.addMiddleware(...middlewares)
|
| 83 |
+
return useDispatch
|
| 84 |
+
}
|
| 85 |
+
createDispatchWithMiddlewareHook.withTypes = () =>
|
| 86 |
+
createDispatchWithMiddlewareHook
|
| 87 |
+
return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<
|
| 88 |
+
State,
|
| 89 |
+
DispatchType
|
| 90 |
+
>
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
const createDispatchWithMiddlewareHook =
|
| 94 |
+
createDispatchWithMiddlewareHookFactory()
|
| 95 |
+
|
| 96 |
+
return {
|
| 97 |
+
...instance,
|
| 98 |
+
createDispatchWithMiddlewareHookFactory,
|
| 99 |
+
createDispatchWithMiddlewareHook,
|
| 100 |
+
}
|
| 101 |
+
}
|
node_modules/@reduxjs/toolkit/src/dynamicMiddleware/types.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Dispatch, Middleware, MiddlewareAPI, UnknownAction } from 'redux'
|
| 2 |
+
import type { BaseActionCreator, PayloadAction } from '../createAction'
|
| 3 |
+
import type { GetState } from '../createAsyncThunk'
|
| 4 |
+
import type { ExtractDispatchExtensions, FallbackIfUnknown } from '../tsHelpers'
|
| 5 |
+
|
| 6 |
+
export type GetMiddlewareApi<MiddlewareApiConfig> = MiddlewareAPI<
|
| 7 |
+
GetDispatchType<MiddlewareApiConfig>,
|
| 8 |
+
GetState<MiddlewareApiConfig>
|
| 9 |
+
>
|
| 10 |
+
|
| 11 |
+
export type MiddlewareApiConfig = {
|
| 12 |
+
state?: unknown
|
| 13 |
+
dispatch?: Dispatch
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
// TODO: consolidate with cAT helpers?
|
| 17 |
+
export type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
|
| 18 |
+
dispatch: infer DispatchType
|
| 19 |
+
}
|
| 20 |
+
? FallbackIfUnknown<DispatchType, Dispatch>
|
| 21 |
+
: Dispatch
|
| 22 |
+
|
| 23 |
+
export type AddMiddleware<
|
| 24 |
+
State = any,
|
| 25 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 26 |
+
> = {
|
| 27 |
+
(...middlewares: Middleware<any, State, DispatchType>[]): void
|
| 28 |
+
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<
|
| 29 |
+
GetState<MiddlewareConfig>,
|
| 30 |
+
GetDispatchType<MiddlewareConfig>
|
| 31 |
+
>
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
export type WithMiddleware<
|
| 35 |
+
State = any,
|
| 36 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 37 |
+
> = BaseActionCreator<
|
| 38 |
+
Middleware<any, State, DispatchType>[],
|
| 39 |
+
'dynamicMiddleware/add',
|
| 40 |
+
{ instanceId: string }
|
| 41 |
+
> & {
|
| 42 |
+
<Middlewares extends Middleware<any, State, DispatchType>[]>(
|
| 43 |
+
...middlewares: Middlewares
|
| 44 |
+
): PayloadAction<Middlewares, 'dynamicMiddleware/add', { instanceId: string }>
|
| 45 |
+
withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<
|
| 46 |
+
GetState<MiddlewareConfig>,
|
| 47 |
+
GetDispatchType<MiddlewareConfig>
|
| 48 |
+
>
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
export interface DynamicDispatch {
|
| 52 |
+
// return a version of dispatch that knows about middleware
|
| 53 |
+
<Middlewares extends Middleware<any>[]>(
|
| 54 |
+
action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>,
|
| 55 |
+
): ExtractDispatchExtensions<Middlewares> & this
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
export type MiddlewareEntry<
|
| 59 |
+
State = unknown,
|
| 60 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 61 |
+
> = {
|
| 62 |
+
middleware: Middleware<any, State, DispatchType>
|
| 63 |
+
applied: Map<
|
| 64 |
+
MiddlewareAPI<DispatchType, State>,
|
| 65 |
+
ReturnType<Middleware<any, State, DispatchType>>
|
| 66 |
+
>
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
export type DynamicMiddleware<
|
| 70 |
+
State = unknown,
|
| 71 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 72 |
+
> = Middleware<DynamicDispatch, State, DispatchType>
|
| 73 |
+
|
| 74 |
+
export type DynamicMiddlewareInstance<
|
| 75 |
+
State = unknown,
|
| 76 |
+
DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,
|
| 77 |
+
> = {
|
| 78 |
+
middleware: DynamicMiddleware<State, DispatchType>
|
| 79 |
+
addMiddleware: AddMiddleware<State, DispatchType>
|
| 80 |
+
withMiddleware: WithMiddleware<State, DispatchType>
|
| 81 |
+
instanceId: string
|
| 82 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/create_adapter.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'
|
| 2 |
+
import { createInitialStateFactory } from './entity_state'
|
| 3 |
+
import { createSelectorsFactory } from './state_selectors'
|
| 4 |
+
import { createSortedStateAdapter } from './sorted_state_adapter'
|
| 5 |
+
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
|
| 6 |
+
import type { WithRequiredProp } from '../tsHelpers'
|
| 7 |
+
|
| 8 |
+
export function createEntityAdapter<T, Id extends EntityId>(
|
| 9 |
+
options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,
|
| 10 |
+
): EntityAdapter<T, Id>
|
| 11 |
+
|
| 12 |
+
export function createEntityAdapter<T extends { id: EntityId }>(
|
| 13 |
+
options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,
|
| 14 |
+
): EntityAdapter<T, T['id']>
|
| 15 |
+
|
| 16 |
+
/**
|
| 17 |
+
*
|
| 18 |
+
* @param options
|
| 19 |
+
*
|
| 20 |
+
* @public
|
| 21 |
+
*/
|
| 22 |
+
export function createEntityAdapter<T>(
|
| 23 |
+
options: EntityAdapterOptions<T, EntityId> = {},
|
| 24 |
+
): EntityAdapter<T, EntityId> {
|
| 25 |
+
const {
|
| 26 |
+
selectId,
|
| 27 |
+
sortComparer,
|
| 28 |
+
}: Required<EntityAdapterOptions<T, EntityId>> = {
|
| 29 |
+
sortComparer: false,
|
| 30 |
+
selectId: (instance: any) => instance.id,
|
| 31 |
+
...options,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
const stateAdapter = sortComparer
|
| 35 |
+
? createSortedStateAdapter(selectId, sortComparer)
|
| 36 |
+
: createUnsortedStateAdapter(selectId)
|
| 37 |
+
const stateFactory = createInitialStateFactory(stateAdapter)
|
| 38 |
+
const selectorsFactory = createSelectorsFactory<T, EntityId>()
|
| 39 |
+
|
| 40 |
+
return {
|
| 41 |
+
selectId,
|
| 42 |
+
sortComparer,
|
| 43 |
+
...stateFactory,
|
| 44 |
+
...selectorsFactory,
|
| 45 |
+
...stateAdapter,
|
| 46 |
+
}
|
| 47 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/entity_state.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {
|
| 2 |
+
EntityId,
|
| 3 |
+
EntityState,
|
| 4 |
+
EntityStateAdapter,
|
| 5 |
+
EntityStateFactory,
|
| 6 |
+
} from './models'
|
| 7 |
+
|
| 8 |
+
export function getInitialEntityState<T, Id extends EntityId>(): EntityState<
|
| 9 |
+
T,
|
| 10 |
+
Id
|
| 11 |
+
> {
|
| 12 |
+
return {
|
| 13 |
+
ids: [],
|
| 14 |
+
entities: {} as Record<Id, T>,
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
export function createInitialStateFactory<T, Id extends EntityId>(
|
| 19 |
+
stateAdapter: EntityStateAdapter<T, Id>,
|
| 20 |
+
): EntityStateFactory<T, Id> {
|
| 21 |
+
function getInitialState(
|
| 22 |
+
state?: undefined,
|
| 23 |
+
entities?: readonly T[] | Record<Id, T>,
|
| 24 |
+
): EntityState<T, Id>
|
| 25 |
+
function getInitialState<S extends object>(
|
| 26 |
+
additionalState: S,
|
| 27 |
+
entities?: readonly T[] | Record<Id, T>,
|
| 28 |
+
): EntityState<T, Id> & S
|
| 29 |
+
function getInitialState(
|
| 30 |
+
additionalState: any = {},
|
| 31 |
+
entities?: readonly T[] | Record<Id, T>,
|
| 32 |
+
): any {
|
| 33 |
+
const state = Object.assign(getInitialEntityState(), additionalState)
|
| 34 |
+
return entities ? stateAdapter.setAll(state, entities) : state
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
return { getInitialState }
|
| 38 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export { createEntityAdapter } from './create_adapter'
|
| 2 |
+
export type {
|
| 3 |
+
EntityState,
|
| 4 |
+
EntityAdapter,
|
| 5 |
+
Update,
|
| 6 |
+
IdSelector,
|
| 7 |
+
Comparer,
|
| 8 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Draft } from 'immer'
|
| 2 |
+
import type { PayloadAction } from '../createAction'
|
| 3 |
+
import type { CastAny, Id } from '../tsHelpers'
|
| 4 |
+
import type { UncheckedIndexedAccess } from '../uncheckedindexed.js'
|
| 5 |
+
import type { GetSelectorsOptions } from './state_selectors'
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* @public
|
| 9 |
+
*/
|
| 10 |
+
export type EntityId = number | string
|
| 11 |
+
|
| 12 |
+
/**
|
| 13 |
+
* @public
|
| 14 |
+
*/
|
| 15 |
+
export type Comparer<T> = (a: T, b: T) => number
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* @public
|
| 19 |
+
*/
|
| 20 |
+
export type IdSelector<T, Id extends EntityId> = (model: T) => Id
|
| 21 |
+
|
| 22 |
+
/**
|
| 23 |
+
* @public
|
| 24 |
+
*/
|
| 25 |
+
export type Update<T, Id extends EntityId> = { id: Id; changes: Partial<T> }
|
| 26 |
+
|
| 27 |
+
/**
|
| 28 |
+
* @public
|
| 29 |
+
*/
|
| 30 |
+
export interface EntityState<T, Id extends EntityId> {
|
| 31 |
+
ids: Id[]
|
| 32 |
+
entities: Record<Id, T>
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/**
|
| 36 |
+
* @public
|
| 37 |
+
*/
|
| 38 |
+
export interface EntityAdapterOptions<T, Id extends EntityId> {
|
| 39 |
+
selectId?: IdSelector<T, Id>
|
| 40 |
+
sortComparer?: false | Comparer<T>
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export type PreventAny<S, T, Id extends EntityId> = CastAny<
|
| 44 |
+
S,
|
| 45 |
+
EntityState<T, Id>
|
| 46 |
+
>
|
| 47 |
+
|
| 48 |
+
export type DraftableEntityState<T, Id extends EntityId> =
|
| 49 |
+
| EntityState<T, Id>
|
| 50 |
+
| Draft<EntityState<T, Id>>
|
| 51 |
+
|
| 52 |
+
/**
|
| 53 |
+
* @public
|
| 54 |
+
*/
|
| 55 |
+
export interface EntityStateAdapter<T, Id extends EntityId> {
|
| 56 |
+
addOne<S extends DraftableEntityState<T, Id>>(
|
| 57 |
+
state: PreventAny<S, T, Id>,
|
| 58 |
+
entity: T,
|
| 59 |
+
): S
|
| 60 |
+
addOne<S extends DraftableEntityState<T, Id>>(
|
| 61 |
+
state: PreventAny<S, T, Id>,
|
| 62 |
+
action: PayloadAction<T>,
|
| 63 |
+
): S
|
| 64 |
+
|
| 65 |
+
addMany<S extends DraftableEntityState<T, Id>>(
|
| 66 |
+
state: PreventAny<S, T, Id>,
|
| 67 |
+
entities: readonly T[] | Record<Id, T>,
|
| 68 |
+
): S
|
| 69 |
+
addMany<S extends DraftableEntityState<T, Id>>(
|
| 70 |
+
state: PreventAny<S, T, Id>,
|
| 71 |
+
entities: PayloadAction<readonly T[] | Record<Id, T>>,
|
| 72 |
+
): S
|
| 73 |
+
|
| 74 |
+
setOne<S extends DraftableEntityState<T, Id>>(
|
| 75 |
+
state: PreventAny<S, T, Id>,
|
| 76 |
+
entity: T,
|
| 77 |
+
): S
|
| 78 |
+
setOne<S extends DraftableEntityState<T, Id>>(
|
| 79 |
+
state: PreventAny<S, T, Id>,
|
| 80 |
+
action: PayloadAction<T>,
|
| 81 |
+
): S
|
| 82 |
+
setMany<S extends DraftableEntityState<T, Id>>(
|
| 83 |
+
state: PreventAny<S, T, Id>,
|
| 84 |
+
entities: readonly T[] | Record<Id, T>,
|
| 85 |
+
): S
|
| 86 |
+
setMany<S extends DraftableEntityState<T, Id>>(
|
| 87 |
+
state: PreventAny<S, T, Id>,
|
| 88 |
+
entities: PayloadAction<readonly T[] | Record<Id, T>>,
|
| 89 |
+
): S
|
| 90 |
+
setAll<S extends DraftableEntityState<T, Id>>(
|
| 91 |
+
state: PreventAny<S, T, Id>,
|
| 92 |
+
entities: readonly T[] | Record<Id, T>,
|
| 93 |
+
): S
|
| 94 |
+
setAll<S extends DraftableEntityState<T, Id>>(
|
| 95 |
+
state: PreventAny<S, T, Id>,
|
| 96 |
+
entities: PayloadAction<readonly T[] | Record<Id, T>>,
|
| 97 |
+
): S
|
| 98 |
+
|
| 99 |
+
removeOne<S extends DraftableEntityState<T, Id>>(
|
| 100 |
+
state: PreventAny<S, T, Id>,
|
| 101 |
+
key: Id,
|
| 102 |
+
): S
|
| 103 |
+
removeOne<S extends DraftableEntityState<T, Id>>(
|
| 104 |
+
state: PreventAny<S, T, Id>,
|
| 105 |
+
key: PayloadAction<Id>,
|
| 106 |
+
): S
|
| 107 |
+
|
| 108 |
+
removeMany<S extends DraftableEntityState<T, Id>>(
|
| 109 |
+
state: PreventAny<S, T, Id>,
|
| 110 |
+
keys: readonly Id[],
|
| 111 |
+
): S
|
| 112 |
+
removeMany<S extends DraftableEntityState<T, Id>>(
|
| 113 |
+
state: PreventAny<S, T, Id>,
|
| 114 |
+
keys: PayloadAction<readonly Id[]>,
|
| 115 |
+
): S
|
| 116 |
+
|
| 117 |
+
removeAll<S extends DraftableEntityState<T, Id>>(
|
| 118 |
+
state: PreventAny<S, T, Id>,
|
| 119 |
+
): S
|
| 120 |
+
|
| 121 |
+
updateOne<S extends DraftableEntityState<T, Id>>(
|
| 122 |
+
state: PreventAny<S, T, Id>,
|
| 123 |
+
update: Update<T, Id>,
|
| 124 |
+
): S
|
| 125 |
+
updateOne<S extends DraftableEntityState<T, Id>>(
|
| 126 |
+
state: PreventAny<S, T, Id>,
|
| 127 |
+
update: PayloadAction<Update<T, Id>>,
|
| 128 |
+
): S
|
| 129 |
+
|
| 130 |
+
updateMany<S extends DraftableEntityState<T, Id>>(
|
| 131 |
+
state: PreventAny<S, T, Id>,
|
| 132 |
+
updates: ReadonlyArray<Update<T, Id>>,
|
| 133 |
+
): S
|
| 134 |
+
updateMany<S extends DraftableEntityState<T, Id>>(
|
| 135 |
+
state: PreventAny<S, T, Id>,
|
| 136 |
+
updates: PayloadAction<ReadonlyArray<Update<T, Id>>>,
|
| 137 |
+
): S
|
| 138 |
+
|
| 139 |
+
upsertOne<S extends DraftableEntityState<T, Id>>(
|
| 140 |
+
state: PreventAny<S, T, Id>,
|
| 141 |
+
entity: T,
|
| 142 |
+
): S
|
| 143 |
+
upsertOne<S extends DraftableEntityState<T, Id>>(
|
| 144 |
+
state: PreventAny<S, T, Id>,
|
| 145 |
+
entity: PayloadAction<T>,
|
| 146 |
+
): S
|
| 147 |
+
|
| 148 |
+
upsertMany<S extends DraftableEntityState<T, Id>>(
|
| 149 |
+
state: PreventAny<S, T, Id>,
|
| 150 |
+
entities: readonly T[] | Record<Id, T>,
|
| 151 |
+
): S
|
| 152 |
+
upsertMany<S extends DraftableEntityState<T, Id>>(
|
| 153 |
+
state: PreventAny<S, T, Id>,
|
| 154 |
+
entities: PayloadAction<readonly T[] | Record<Id, T>>,
|
| 155 |
+
): S
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/**
|
| 159 |
+
* @public
|
| 160 |
+
*/
|
| 161 |
+
export interface EntitySelectors<T, V, IdType extends EntityId> {
|
| 162 |
+
selectIds: (state: V) => IdType[]
|
| 163 |
+
selectEntities: (state: V) => Record<IdType, T>
|
| 164 |
+
selectAll: (state: V) => T[]
|
| 165 |
+
selectTotal: (state: V) => number
|
| 166 |
+
selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
/**
|
| 170 |
+
* @public
|
| 171 |
+
*/
|
| 172 |
+
export interface EntityStateFactory<T, Id extends EntityId> {
|
| 173 |
+
getInitialState(
|
| 174 |
+
state?: undefined,
|
| 175 |
+
entities?: Record<Id, T> | readonly T[],
|
| 176 |
+
): EntityState<T, Id>
|
| 177 |
+
getInitialState<S extends object>(
|
| 178 |
+
state: S,
|
| 179 |
+
entities?: Record<Id, T> | readonly T[],
|
| 180 |
+
): EntityState<T, Id> & S
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
/**
|
| 184 |
+
* @public
|
| 185 |
+
*/
|
| 186 |
+
export interface EntityAdapter<T, Id extends EntityId>
|
| 187 |
+
extends EntityStateAdapter<T, Id>,
|
| 188 |
+
EntityStateFactory<T, Id>,
|
| 189 |
+
Required<EntityAdapterOptions<T, Id>> {
|
| 190 |
+
getSelectors(
|
| 191 |
+
selectState?: undefined,
|
| 192 |
+
options?: GetSelectorsOptions,
|
| 193 |
+
): EntitySelectors<T, EntityState<T, Id>, Id>
|
| 194 |
+
getSelectors<V>(
|
| 195 |
+
selectState: (state: V) => EntityState<T, Id>,
|
| 196 |
+
options?: GetSelectorsOptions,
|
| 197 |
+
): EntitySelectors<T, V, Id>
|
| 198 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/sorted_state_adapter.ts
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {
|
| 2 |
+
IdSelector,
|
| 3 |
+
Comparer,
|
| 4 |
+
EntityStateAdapter,
|
| 5 |
+
Update,
|
| 6 |
+
EntityId,
|
| 7 |
+
DraftableEntityState,
|
| 8 |
+
} from './models'
|
| 9 |
+
import { createStateOperator } from './state_adapter'
|
| 10 |
+
import { createUnsortedStateAdapter } from './unsorted_state_adapter'
|
| 11 |
+
import {
|
| 12 |
+
selectIdValue,
|
| 13 |
+
ensureEntitiesArray,
|
| 14 |
+
splitAddedUpdatedEntities,
|
| 15 |
+
getCurrent,
|
| 16 |
+
} from './utils'
|
| 17 |
+
|
| 18 |
+
// Borrowed from Replay
|
| 19 |
+
export function findInsertIndex<T>(
|
| 20 |
+
sortedItems: T[],
|
| 21 |
+
item: T,
|
| 22 |
+
comparisonFunction: Comparer<T>,
|
| 23 |
+
): number {
|
| 24 |
+
let lowIndex = 0
|
| 25 |
+
let highIndex = sortedItems.length
|
| 26 |
+
while (lowIndex < highIndex) {
|
| 27 |
+
let middleIndex = (lowIndex + highIndex) >>> 1
|
| 28 |
+
const currentItem = sortedItems[middleIndex]
|
| 29 |
+
const res = comparisonFunction(item, currentItem)
|
| 30 |
+
if (res >= 0) {
|
| 31 |
+
lowIndex = middleIndex + 1
|
| 32 |
+
} else {
|
| 33 |
+
highIndex = middleIndex
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
return lowIndex
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
export function insert<T>(
|
| 41 |
+
sortedItems: T[],
|
| 42 |
+
item: T,
|
| 43 |
+
comparisonFunction: Comparer<T>,
|
| 44 |
+
): T[] {
|
| 45 |
+
const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction)
|
| 46 |
+
|
| 47 |
+
sortedItems.splice(insertAtIndex, 0, item)
|
| 48 |
+
|
| 49 |
+
return sortedItems
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
export function createSortedStateAdapter<T, Id extends EntityId>(
|
| 53 |
+
selectId: IdSelector<T, Id>,
|
| 54 |
+
comparer: Comparer<T>,
|
| 55 |
+
): EntityStateAdapter<T, Id> {
|
| 56 |
+
type R = DraftableEntityState<T, Id>
|
| 57 |
+
|
| 58 |
+
const { removeOne, removeMany, removeAll } =
|
| 59 |
+
createUnsortedStateAdapter(selectId)
|
| 60 |
+
|
| 61 |
+
function addOneMutably(entity: T, state: R): void {
|
| 62 |
+
return addManyMutably([entity], state)
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
function addManyMutably(
|
| 66 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 67 |
+
state: R,
|
| 68 |
+
existingIds?: Id[],
|
| 69 |
+
): void {
|
| 70 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 71 |
+
|
| 72 |
+
const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids))
|
| 73 |
+
const addedKeys = new Set<Id>();
|
| 74 |
+
const models = newEntities.filter(
|
| 75 |
+
(model) => {
|
| 76 |
+
const modelId = selectIdValue(model, selectId);
|
| 77 |
+
const notAdded = !addedKeys.has(modelId);
|
| 78 |
+
if (notAdded) addedKeys.add(modelId);
|
| 79 |
+
return !existingKeys.has(modelId) && notAdded;
|
| 80 |
+
}
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if (models.length !== 0) {
|
| 84 |
+
mergeFunction(state, models)
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
function setOneMutably(entity: T, state: R): void {
|
| 89 |
+
return setManyMutably([entity], state)
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
function setManyMutably(
|
| 93 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 94 |
+
state: R,
|
| 95 |
+
): void {
|
| 96 |
+
let deduplicatedEntities = {} as Record<Id, T>;
|
| 97 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 98 |
+
if (newEntities.length !== 0) {
|
| 99 |
+
for (const item of newEntities) {
|
| 100 |
+
const entityId = selectId(item);
|
| 101 |
+
// For multiple items with the same ID, we should keep the last one.
|
| 102 |
+
deduplicatedEntities[entityId] = item;
|
| 103 |
+
delete (state.entities as Record<Id, T>)[entityId]
|
| 104 |
+
}
|
| 105 |
+
newEntities = ensureEntitiesArray(deduplicatedEntities);
|
| 106 |
+
mergeFunction(state, newEntities)
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
function setAllMutably(
|
| 111 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 112 |
+
state: R,
|
| 113 |
+
): void {
|
| 114 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 115 |
+
state.entities = {} as Record<Id, T>
|
| 116 |
+
state.ids = []
|
| 117 |
+
|
| 118 |
+
addManyMutably(newEntities, state, [])
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
function updateOneMutably(update: Update<T, Id>, state: R): void {
|
| 122 |
+
return updateManyMutably([update], state)
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
function updateManyMutably(
|
| 126 |
+
updates: ReadonlyArray<Update<T, Id>>,
|
| 127 |
+
state: R,
|
| 128 |
+
): void {
|
| 129 |
+
let appliedUpdates = false
|
| 130 |
+
let replacedIds = false
|
| 131 |
+
|
| 132 |
+
for (let update of updates) {
|
| 133 |
+
const entity: T | undefined = (state.entities as Record<Id, T>)[update.id]
|
| 134 |
+
if (!entity) {
|
| 135 |
+
continue
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
appliedUpdates = true
|
| 139 |
+
|
| 140 |
+
Object.assign(entity, update.changes)
|
| 141 |
+
const newId = selectId(entity)
|
| 142 |
+
|
| 143 |
+
if (update.id !== newId) {
|
| 144 |
+
// We do support the case where updates can change an item's ID.
|
| 145 |
+
// This makes things trickier - go ahead and swap the IDs in state now.
|
| 146 |
+
replacedIds = true
|
| 147 |
+
delete (state.entities as Record<Id, T>)[update.id]
|
| 148 |
+
const oldIndex = (state.ids as Id[]).indexOf(update.id)
|
| 149 |
+
state.ids[oldIndex] = newId
|
| 150 |
+
;(state.entities as Record<Id, T>)[newId] = entity
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
if (appliedUpdates) {
|
| 155 |
+
mergeFunction(state, [], appliedUpdates, replacedIds)
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
function upsertOneMutably(entity: T, state: R): void {
|
| 160 |
+
return upsertManyMutably([entity], state)
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
function upsertManyMutably(
|
| 164 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 165 |
+
state: R,
|
| 166 |
+
): void {
|
| 167 |
+
const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(
|
| 168 |
+
newEntities,
|
| 169 |
+
selectId,
|
| 170 |
+
state,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if (added.length) {
|
| 174 |
+
addManyMutably(added, state, existingIdsArray)
|
| 175 |
+
}
|
| 176 |
+
if (updated.length) {
|
| 177 |
+
updateManyMutably(updated, state)
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {
|
| 182 |
+
if (a.length !== b.length) {
|
| 183 |
+
return false
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
for (let i = 0; i < a.length; i++) {
|
| 187 |
+
if (a[i] === b[i]) {
|
| 188 |
+
continue
|
| 189 |
+
}
|
| 190 |
+
return false
|
| 191 |
+
}
|
| 192 |
+
return true
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
type MergeFunction = (
|
| 196 |
+
state: R,
|
| 197 |
+
addedItems: readonly T[],
|
| 198 |
+
appliedUpdates?: boolean,
|
| 199 |
+
replacedIds?: boolean,
|
| 200 |
+
) => void
|
| 201 |
+
|
| 202 |
+
const mergeFunction: MergeFunction = (
|
| 203 |
+
state,
|
| 204 |
+
addedItems,
|
| 205 |
+
appliedUpdates,
|
| 206 |
+
replacedIds,
|
| 207 |
+
) => {
|
| 208 |
+
const currentEntities = getCurrent(state.entities)
|
| 209 |
+
const currentIds = getCurrent(state.ids)
|
| 210 |
+
|
| 211 |
+
const stateEntities = state.entities as Record<Id, T>
|
| 212 |
+
|
| 213 |
+
let ids: Iterable<Id> = currentIds
|
| 214 |
+
if (replacedIds) {
|
| 215 |
+
ids = new Set(currentIds)
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
let sortedEntities: T[] = []
|
| 219 |
+
for (const id of ids) {
|
| 220 |
+
const entity = currentEntities[id]
|
| 221 |
+
if (entity) {
|
| 222 |
+
sortedEntities.push(entity)
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
const wasPreviouslyEmpty = sortedEntities.length === 0
|
| 226 |
+
|
| 227 |
+
// Insert/overwrite all new/updated
|
| 228 |
+
for (const item of addedItems) {
|
| 229 |
+
stateEntities[selectId(item)] = item
|
| 230 |
+
|
| 231 |
+
if (!wasPreviouslyEmpty) {
|
| 232 |
+
// Binary search insertion generally requires fewer comparisons
|
| 233 |
+
insert(sortedEntities, item, comparer)
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
if (wasPreviouslyEmpty) {
|
| 238 |
+
// All we have is the incoming values, sort them
|
| 239 |
+
sortedEntities = addedItems.slice().sort(comparer)
|
| 240 |
+
} else if (appliedUpdates) {
|
| 241 |
+
// We should have a _mostly_-sorted array already
|
| 242 |
+
sortedEntities.sort(comparer)
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
const newSortedIds = sortedEntities.map(selectId)
|
| 246 |
+
|
| 247 |
+
if (!areArraysEqual(currentIds, newSortedIds)) {
|
| 248 |
+
state.ids = newSortedIds
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
return {
|
| 253 |
+
removeOne,
|
| 254 |
+
removeMany,
|
| 255 |
+
removeAll,
|
| 256 |
+
addOne: createStateOperator(addOneMutably),
|
| 257 |
+
updateOne: createStateOperator(updateOneMutably),
|
| 258 |
+
upsertOne: createStateOperator(upsertOneMutably),
|
| 259 |
+
setOne: createStateOperator(setOneMutably),
|
| 260 |
+
setMany: createStateOperator(setManyMutably),
|
| 261 |
+
setAll: createStateOperator(setAllMutably),
|
| 262 |
+
addMany: createStateOperator(addManyMutably),
|
| 263 |
+
updateMany: createStateOperator(updateManyMutably),
|
| 264 |
+
upsertMany: createStateOperator(upsertManyMutably),
|
| 265 |
+
}
|
| 266 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/state_adapter.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createNextState, isDraft } from '../immerImports'
|
| 2 |
+
import type { Draft } from 'immer'
|
| 3 |
+
import type { EntityId, DraftableEntityState, PreventAny } from './models'
|
| 4 |
+
import type { PayloadAction } from '../createAction'
|
| 5 |
+
import { isFSA } from '../createAction'
|
| 6 |
+
|
| 7 |
+
export const isDraftTyped = isDraft as <T>(
|
| 8 |
+
value: T | Draft<T>,
|
| 9 |
+
) => value is Draft<T>
|
| 10 |
+
|
| 11 |
+
export function createSingleArgumentStateOperator<T, Id extends EntityId>(
|
| 12 |
+
mutator: (state: DraftableEntityState<T, Id>) => void,
|
| 13 |
+
) {
|
| 14 |
+
const operator = createStateOperator(
|
| 15 |
+
(_: undefined, state: DraftableEntityState<T, Id>) => mutator(state),
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
return function operation<S extends DraftableEntityState<T, Id>>(
|
| 19 |
+
state: PreventAny<S, T, Id>,
|
| 20 |
+
): S {
|
| 21 |
+
return operator(state as S, undefined)
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
export function createStateOperator<T, Id extends EntityId, R>(
|
| 26 |
+
mutator: (arg: R, state: DraftableEntityState<T, Id>) => void,
|
| 27 |
+
) {
|
| 28 |
+
return function operation<S extends DraftableEntityState<T, Id>>(
|
| 29 |
+
state: S,
|
| 30 |
+
arg: R | PayloadAction<R>,
|
| 31 |
+
): S {
|
| 32 |
+
function isPayloadActionArgument(
|
| 33 |
+
arg: R | PayloadAction<R>,
|
| 34 |
+
): arg is PayloadAction<R> {
|
| 35 |
+
return isFSA(arg)
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
const runMutator = (draft: DraftableEntityState<T, Id>) => {
|
| 39 |
+
if (isPayloadActionArgument(arg)) {
|
| 40 |
+
mutator(arg.payload, draft)
|
| 41 |
+
} else {
|
| 42 |
+
mutator(arg, draft)
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {
|
| 47 |
+
// we must already be inside a `createNextState` call, likely because
|
| 48 |
+
// this is being wrapped in `createReducer` or `createSlice`.
|
| 49 |
+
// It's safe to just pass the draft to the mutator.
|
| 50 |
+
runMutator(state)
|
| 51 |
+
|
| 52 |
+
// since it's a draft, we'll just return it
|
| 53 |
+
return state
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
return createNextState(state, runMutator)
|
| 57 |
+
}
|
| 58 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CreateSelectorFunction, Selector } from 'reselect'
|
| 2 |
+
import { createDraftSafeSelector } from '../createDraftSafeSelector'
|
| 3 |
+
import type { EntityId, EntitySelectors, EntityState } from './models'
|
| 4 |
+
|
| 5 |
+
type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>
|
| 6 |
+
|
| 7 |
+
export type GetSelectorsOptions = {
|
| 8 |
+
createSelector?: AnyCreateSelectorFunction
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
export function createSelectorsFactory<T, Id extends EntityId>() {
|
| 12 |
+
function getSelectors(
|
| 13 |
+
selectState?: undefined,
|
| 14 |
+
options?: GetSelectorsOptions,
|
| 15 |
+
): EntitySelectors<T, EntityState<T, Id>, Id>
|
| 16 |
+
function getSelectors<V>(
|
| 17 |
+
selectState: (state: V) => EntityState<T, Id>,
|
| 18 |
+
options?: GetSelectorsOptions,
|
| 19 |
+
): EntitySelectors<T, V, Id>
|
| 20 |
+
function getSelectors<V>(
|
| 21 |
+
selectState?: (state: V) => EntityState<T, Id>,
|
| 22 |
+
options: GetSelectorsOptions = {},
|
| 23 |
+
): EntitySelectors<T, any, Id> {
|
| 24 |
+
const {
|
| 25 |
+
createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,
|
| 26 |
+
} = options
|
| 27 |
+
|
| 28 |
+
const selectIds = (state: EntityState<T, Id>) => state.ids
|
| 29 |
+
|
| 30 |
+
const selectEntities = (state: EntityState<T, Id>) => state.entities
|
| 31 |
+
|
| 32 |
+
const selectAll = createSelector(
|
| 33 |
+
selectIds,
|
| 34 |
+
selectEntities,
|
| 35 |
+
(ids, entities): T[] => ids.map((id) => entities[id]!),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
const selectId = (_: unknown, id: Id) => id
|
| 39 |
+
|
| 40 |
+
const selectById = (entities: Record<Id, T>, id: Id) => entities[id]
|
| 41 |
+
|
| 42 |
+
const selectTotal = createSelector(selectIds, (ids) => ids.length)
|
| 43 |
+
|
| 44 |
+
if (!selectState) {
|
| 45 |
+
return {
|
| 46 |
+
selectIds,
|
| 47 |
+
selectEntities,
|
| 48 |
+
selectAll,
|
| 49 |
+
selectTotal,
|
| 50 |
+
selectById: createSelector(selectEntities, selectId, selectById),
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
const selectGlobalizedEntities = createSelector(
|
| 55 |
+
selectState as Selector<V, EntityState<T, Id>>,
|
| 56 |
+
selectEntities,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
return {
|
| 60 |
+
selectIds: createSelector(selectState, selectIds),
|
| 61 |
+
selectEntities: selectGlobalizedEntities,
|
| 62 |
+
selectAll: createSelector(selectState, selectAll),
|
| 63 |
+
selectTotal: createSelector(selectState, selectTotal),
|
| 64 |
+
selectById: createSelector(
|
| 65 |
+
selectGlobalizedEntities,
|
| 66 |
+
selectId,
|
| 67 |
+
selectById,
|
| 68 |
+
),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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Draft } from 'immer'
|
| 2 |
+
import type {
|
| 3 |
+
EntityStateAdapter,
|
| 4 |
+
IdSelector,
|
| 5 |
+
Update,
|
| 6 |
+
EntityId,
|
| 7 |
+
DraftableEntityState,
|
| 8 |
+
} from './models'
|
| 9 |
+
import {
|
| 10 |
+
createStateOperator,
|
| 11 |
+
createSingleArgumentStateOperator,
|
| 12 |
+
} from './state_adapter'
|
| 13 |
+
import {
|
| 14 |
+
selectIdValue,
|
| 15 |
+
ensureEntitiesArray,
|
| 16 |
+
splitAddedUpdatedEntities,
|
| 17 |
+
} from './utils'
|
| 18 |
+
|
| 19 |
+
export function createUnsortedStateAdapter<T, Id extends EntityId>(
|
| 20 |
+
selectId: IdSelector<T, Id>,
|
| 21 |
+
): EntityStateAdapter<T, Id> {
|
| 22 |
+
type R = DraftableEntityState<T, Id>
|
| 23 |
+
|
| 24 |
+
function addOneMutably(entity: T, state: R): void {
|
| 25 |
+
const key = selectIdValue(entity, selectId)
|
| 26 |
+
|
| 27 |
+
if (key in state.entities) {
|
| 28 |
+
return
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
state.ids.push(key as Id & Draft<Id>)
|
| 32 |
+
;(state.entities as Record<Id, T>)[key] = entity
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
function addManyMutably(
|
| 36 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 37 |
+
state: R,
|
| 38 |
+
): void {
|
| 39 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 40 |
+
|
| 41 |
+
for (const entity of newEntities) {
|
| 42 |
+
addOneMutably(entity, state)
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
function setOneMutably(entity: T, state: R): void {
|
| 47 |
+
const key = selectIdValue(entity, selectId)
|
| 48 |
+
if (!(key in state.entities)) {
|
| 49 |
+
state.ids.push(key as Id & Draft<Id>)
|
| 50 |
+
}
|
| 51 |
+
;(state.entities as Record<Id, T>)[key] = entity
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
function setManyMutably(
|
| 55 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 56 |
+
state: R,
|
| 57 |
+
): void {
|
| 58 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 59 |
+
for (const entity of newEntities) {
|
| 60 |
+
setOneMutably(entity, state)
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
function setAllMutably(
|
| 65 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 66 |
+
state: R,
|
| 67 |
+
): void {
|
| 68 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 69 |
+
|
| 70 |
+
state.ids = []
|
| 71 |
+
state.entities = {} as Record<Id, T>
|
| 72 |
+
|
| 73 |
+
addManyMutably(newEntities, state)
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
function removeOneMutably(key: Id, state: R): void {
|
| 77 |
+
return removeManyMutably([key], state)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
function removeManyMutably(keys: readonly Id[], state: R): void {
|
| 81 |
+
let didMutate = false
|
| 82 |
+
|
| 83 |
+
keys.forEach((key) => {
|
| 84 |
+
if (key in state.entities) {
|
| 85 |
+
delete (state.entities as Record<Id, T>)[key]
|
| 86 |
+
didMutate = true
|
| 87 |
+
}
|
| 88 |
+
})
|
| 89 |
+
|
| 90 |
+
if (didMutate) {
|
| 91 |
+
state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as
|
| 92 |
+
| Id[]
|
| 93 |
+
| Draft<Id[]>
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
function removeAllMutably(state: R): void {
|
| 98 |
+
Object.assign(state, {
|
| 99 |
+
ids: [],
|
| 100 |
+
entities: {},
|
| 101 |
+
})
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
function takeNewKey(
|
| 105 |
+
keys: { [id: string]: Id },
|
| 106 |
+
update: Update<T, Id>,
|
| 107 |
+
state: R,
|
| 108 |
+
): boolean {
|
| 109 |
+
const original: T | undefined = (state.entities as Record<Id, T>)[update.id]
|
| 110 |
+
if (original === undefined) {
|
| 111 |
+
return false
|
| 112 |
+
}
|
| 113 |
+
const updated: T = Object.assign({}, original, update.changes)
|
| 114 |
+
const newKey = selectIdValue(updated, selectId)
|
| 115 |
+
const hasNewKey = newKey !== update.id
|
| 116 |
+
|
| 117 |
+
if (hasNewKey) {
|
| 118 |
+
keys[update.id] = newKey
|
| 119 |
+
delete (state.entities as Record<Id, T>)[update.id]
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
;(state.entities as Record<Id, T>)[newKey] = updated
|
| 123 |
+
|
| 124 |
+
return hasNewKey
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
function updateOneMutably(update: Update<T, Id>, state: R): void {
|
| 128 |
+
return updateManyMutably([update], state)
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
function updateManyMutably(
|
| 132 |
+
updates: ReadonlyArray<Update<T, Id>>,
|
| 133 |
+
state: R,
|
| 134 |
+
): void {
|
| 135 |
+
const newKeys: { [id: string]: Id } = {}
|
| 136 |
+
|
| 137 |
+
const updatesPerEntity: { [id: string]: Update<T, Id> } = {}
|
| 138 |
+
|
| 139 |
+
updates.forEach((update) => {
|
| 140 |
+
// Only apply updates to entities that currently exist
|
| 141 |
+
if (update.id in state.entities) {
|
| 142 |
+
// If there are multiple updates to one entity, merge them together
|
| 143 |
+
updatesPerEntity[update.id] = {
|
| 144 |
+
id: update.id,
|
| 145 |
+
// Spreads ignore falsy values, so this works even if there isn't
|
| 146 |
+
// an existing update already at this key
|
| 147 |
+
changes: {
|
| 148 |
+
...updatesPerEntity[update.id]?.changes,
|
| 149 |
+
...update.changes,
|
| 150 |
+
},
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
})
|
| 154 |
+
|
| 155 |
+
updates = Object.values(updatesPerEntity)
|
| 156 |
+
|
| 157 |
+
const didMutateEntities = updates.length > 0
|
| 158 |
+
|
| 159 |
+
if (didMutateEntities) {
|
| 160 |
+
const didMutateIds =
|
| 161 |
+
updates.filter((update) => takeNewKey(newKeys, update, state)).length >
|
| 162 |
+
0
|
| 163 |
+
|
| 164 |
+
if (didMutateIds) {
|
| 165 |
+
state.ids = Object.values(state.entities).map((e) =>
|
| 166 |
+
selectIdValue(e as T, selectId),
|
| 167 |
+
)
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
function upsertOneMutably(entity: T, state: R): void {
|
| 173 |
+
return upsertManyMutably([entity], state)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
function upsertManyMutably(
|
| 177 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 178 |
+
state: R,
|
| 179 |
+
): void {
|
| 180 |
+
const [added, updated] = splitAddedUpdatedEntities<T, Id>(
|
| 181 |
+
newEntities,
|
| 182 |
+
selectId,
|
| 183 |
+
state,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
addManyMutably(added, state)
|
| 187 |
+
updateManyMutably(updated, state)
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
return {
|
| 191 |
+
removeAll: createSingleArgumentStateOperator(removeAllMutably),
|
| 192 |
+
addOne: createStateOperator(addOneMutably),
|
| 193 |
+
addMany: createStateOperator(addManyMutably),
|
| 194 |
+
setOne: createStateOperator(setOneMutably),
|
| 195 |
+
setMany: createStateOperator(setManyMutably),
|
| 196 |
+
setAll: createStateOperator(setAllMutably),
|
| 197 |
+
updateOne: createStateOperator(updateOneMutably),
|
| 198 |
+
updateMany: createStateOperator(updateManyMutably),
|
| 199 |
+
upsertOne: createStateOperator(upsertOneMutably),
|
| 200 |
+
upsertMany: createStateOperator(upsertManyMutably),
|
| 201 |
+
removeOne: createStateOperator(removeOneMutably),
|
| 202 |
+
removeMany: createStateOperator(removeManyMutably),
|
| 203 |
+
}
|
| 204 |
+
}
|
node_modules/@reduxjs/toolkit/src/entities/utils.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Draft } from 'immer'
|
| 2 |
+
import { current, isDraft } from '../immerImports'
|
| 3 |
+
import type {
|
| 4 |
+
DraftableEntityState,
|
| 5 |
+
EntityId,
|
| 6 |
+
IdSelector,
|
| 7 |
+
Update,
|
| 8 |
+
} from './models'
|
| 9 |
+
|
| 10 |
+
export function selectIdValue<T, Id extends EntityId>(
|
| 11 |
+
entity: T,
|
| 12 |
+
selectId: IdSelector<T, Id>,
|
| 13 |
+
) {
|
| 14 |
+
const key = selectId(entity)
|
| 15 |
+
|
| 16 |
+
if (process.env.NODE_ENV !== 'production' && key === undefined) {
|
| 17 |
+
console.warn(
|
| 18 |
+
'The entity passed to the `selectId` implementation returned undefined.',
|
| 19 |
+
'You should probably provide your own `selectId` implementation.',
|
| 20 |
+
'The entity that was passed:',
|
| 21 |
+
entity,
|
| 22 |
+
'The `selectId` implementation:',
|
| 23 |
+
selectId.toString(),
|
| 24 |
+
)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
return key
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
export function ensureEntitiesArray<T, Id extends EntityId>(
|
| 31 |
+
entities: readonly T[] | Record<Id, T>,
|
| 32 |
+
): readonly T[] {
|
| 33 |
+
if (!Array.isArray(entities)) {
|
| 34 |
+
entities = Object.values(entities)
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
return entities
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
export function getCurrent<T>(value: T | Draft<T>): T {
|
| 41 |
+
return (isDraft(value) ? current(value) : value) as T
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
export function splitAddedUpdatedEntities<T, Id extends EntityId>(
|
| 45 |
+
newEntities: readonly T[] | Record<Id, T>,
|
| 46 |
+
selectId: IdSelector<T, Id>,
|
| 47 |
+
state: DraftableEntityState<T, Id>,
|
| 48 |
+
): [T[], Update<T, Id>[], Id[]] {
|
| 49 |
+
newEntities = ensureEntitiesArray(newEntities)
|
| 50 |
+
|
| 51 |
+
const existingIdsArray = getCurrent(state.ids)
|
| 52 |
+
const existingIds = new Set<Id>(existingIdsArray)
|
| 53 |
+
|
| 54 |
+
const added: T[] = []
|
| 55 |
+
const addedIds = new Set<Id>([])
|
| 56 |
+
const updated: Update<T, Id>[] = []
|
| 57 |
+
|
| 58 |
+
for (const entity of newEntities) {
|
| 59 |
+
const id = selectIdValue(entity, selectId)
|
| 60 |
+
if (existingIds.has(id) || addedIds.has(id)) {
|
| 61 |
+
updated.push({ id, changes: entity })
|
| 62 |
+
} else {
|
| 63 |
+
addedIds.add(id)
|
| 64 |
+
added.push(entity)
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
return [added, updated, existingIdsArray]
|
| 68 |
+
}
|
node_modules/@reduxjs/toolkit/src/formatProdErrorMessage.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
|
| 3 |
+
*
|
| 4 |
+
* Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
|
| 5 |
+
* during build.
|
| 6 |
+
* @param {number} code
|
| 7 |
+
*/
|
| 8 |
+
export function formatProdErrorMessage(code: number) {
|
| 9 |
+
return (
|
| 10 |
+
`Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` +
|
| 11 |
+
'use the non-minified dev environment for full errors. '
|
| 12 |
+
)
|
| 13 |
+
}
|
node_modules/@reduxjs/toolkit/src/getDefaultEnhancers.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { StoreEnhancer } from 'redux'
|
| 2 |
+
import type { AutoBatchOptions } from './autoBatchEnhancer'
|
| 3 |
+
import { autoBatchEnhancer } from './autoBatchEnhancer'
|
| 4 |
+
import { Tuple } from './utils'
|
| 5 |
+
import type { Middlewares } from './configureStore'
|
| 6 |
+
import type { ExtractDispatchExtensions } from './tsHelpers'
|
| 7 |
+
|
| 8 |
+
type GetDefaultEnhancersOptions = {
|
| 9 |
+
autoBatch?: boolean | AutoBatchOptions
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
export type GetDefaultEnhancers<M extends Middlewares<any>> = (
|
| 13 |
+
options?: GetDefaultEnhancersOptions,
|
| 14 |
+
) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>
|
| 15 |
+
|
| 16 |
+
export const buildGetDefaultEnhancers = <M extends Middlewares<any>>(
|
| 17 |
+
middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>,
|
| 18 |
+
): GetDefaultEnhancers<M> =>
|
| 19 |
+
function getDefaultEnhancers(options) {
|
| 20 |
+
const { autoBatch = true } = options ?? {}
|
| 21 |
+
|
| 22 |
+
let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer)
|
| 23 |
+
if (autoBatch) {
|
| 24 |
+
enhancerArray.push(
|
| 25 |
+
autoBatchEnhancer(
|
| 26 |
+
typeof autoBatch === 'object' ? autoBatch : undefined,
|
| 27 |
+
),
|
| 28 |
+
)
|
| 29 |
+
}
|
| 30 |
+
return enhancerArray as any
|
| 31 |
+
}
|
node_modules/@reduxjs/toolkit/src/getDefaultMiddleware.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Middleware, UnknownAction } from 'redux'
|
| 2 |
+
import type { ThunkMiddleware } from 'redux-thunk'
|
| 3 |
+
import { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk'
|
| 4 |
+
import type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
|
| 5 |
+
import { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
|
| 6 |
+
import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'
|
| 7 |
+
/* PROD_START_REMOVE_UMD */
|
| 8 |
+
import { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'
|
| 9 |
+
/* PROD_STOP_REMOVE_UMD */
|
| 10 |
+
|
| 11 |
+
import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'
|
| 12 |
+
import { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'
|
| 13 |
+
import type { ExcludeFromTuple } from './tsHelpers'
|
| 14 |
+
import { Tuple } from './utils'
|
| 15 |
+
|
| 16 |
+
function isBoolean(x: any): x is boolean {
|
| 17 |
+
return typeof x === 'boolean'
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
interface ThunkOptions<E = any> {
|
| 21 |
+
extraArgument: E
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
interface GetDefaultMiddlewareOptions {
|
| 25 |
+
thunk?: boolean | ThunkOptions
|
| 26 |
+
immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions
|
| 27 |
+
serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions
|
| 28 |
+
actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
export type ThunkMiddlewareFor<
|
| 32 |
+
S,
|
| 33 |
+
O extends GetDefaultMiddlewareOptions = {},
|
| 34 |
+
> = O extends {
|
| 35 |
+
thunk: false
|
| 36 |
+
}
|
| 37 |
+
? never
|
| 38 |
+
: O extends { thunk: { extraArgument: infer E } }
|
| 39 |
+
? ThunkMiddleware<S, UnknownAction, E>
|
| 40 |
+
: ThunkMiddleware<S, UnknownAction>
|
| 41 |
+
|
| 42 |
+
export type GetDefaultMiddleware<S = any> = <
|
| 43 |
+
O extends GetDefaultMiddlewareOptions = {
|
| 44 |
+
thunk: true
|
| 45 |
+
immutableCheck: true
|
| 46 |
+
serializableCheck: true
|
| 47 |
+
actionCreatorCheck: true
|
| 48 |
+
},
|
| 49 |
+
>(
|
| 50 |
+
options?: O,
|
| 51 |
+
) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>
|
| 52 |
+
|
| 53 |
+
export const buildGetDefaultMiddleware = <S = any>(): GetDefaultMiddleware<S> =>
|
| 54 |
+
function getDefaultMiddleware(options) {
|
| 55 |
+
const {
|
| 56 |
+
thunk = true,
|
| 57 |
+
immutableCheck = true,
|
| 58 |
+
serializableCheck = true,
|
| 59 |
+
actionCreatorCheck = true,
|
| 60 |
+
} = options ?? {}
|
| 61 |
+
|
| 62 |
+
let middlewareArray = new Tuple<Middleware[]>()
|
| 63 |
+
|
| 64 |
+
if (thunk) {
|
| 65 |
+
if (isBoolean(thunk)) {
|
| 66 |
+
middlewareArray.push(thunkMiddleware)
|
| 67 |
+
} else {
|
| 68 |
+
middlewareArray.push(withExtraArgument(thunk.extraArgument))
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
if (process.env.NODE_ENV !== 'production') {
|
| 73 |
+
if (immutableCheck) {
|
| 74 |
+
/* PROD_START_REMOVE_UMD */
|
| 75 |
+
let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}
|
| 76 |
+
|
| 77 |
+
if (!isBoolean(immutableCheck)) {
|
| 78 |
+
immutableOptions = immutableCheck
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
middlewareArray.unshift(
|
| 82 |
+
createImmutableStateInvariantMiddleware(immutableOptions),
|
| 83 |
+
)
|
| 84 |
+
/* PROD_STOP_REMOVE_UMD */
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
if (serializableCheck) {
|
| 88 |
+
let serializableOptions: SerializableStateInvariantMiddlewareOptions =
|
| 89 |
+
{}
|
| 90 |
+
|
| 91 |
+
if (!isBoolean(serializableCheck)) {
|
| 92 |
+
serializableOptions = serializableCheck
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
middlewareArray.push(
|
| 96 |
+
createSerializableStateInvariantMiddleware(serializableOptions),
|
| 97 |
+
)
|
| 98 |
+
}
|
| 99 |
+
if (actionCreatorCheck) {
|
| 100 |
+
let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}
|
| 101 |
+
|
| 102 |
+
if (!isBoolean(actionCreatorCheck)) {
|
| 103 |
+
actionCreatorOptions = actionCreatorCheck
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
middlewareArray.unshift(
|
| 107 |
+
createActionCreatorInvariantMiddleware(actionCreatorOptions),
|
| 108 |
+
)
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
return middlewareArray as any
|
| 113 |
+
}
|
node_modules/@reduxjs/toolkit/src/immerImports.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Middleware } from 'redux'
|
| 2 |
+
import type { IgnoredPaths } from './serializableStateInvariantMiddleware'
|
| 3 |
+
import { getTimeMeasureUtils } from './utils'
|
| 4 |
+
|
| 5 |
+
type EntryProcessor = (key: string, value: any) => any
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* The default `isImmutable` function.
|
| 9 |
+
*
|
| 10 |
+
* @public
|
| 11 |
+
*/
|
| 12 |
+
export function isImmutableDefault(value: unknown): boolean {
|
| 13 |
+
return typeof value !== 'object' || value == null || Object.isFrozen(value)
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
export function trackForMutations(
|
| 17 |
+
isImmutable: IsImmutableFunc,
|
| 18 |
+
ignoredPaths: IgnoredPaths | undefined,
|
| 19 |
+
obj: any,
|
| 20 |
+
) {
|
| 21 |
+
const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj)
|
| 22 |
+
return {
|
| 23 |
+
detectMutations() {
|
| 24 |
+
return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj)
|
| 25 |
+
},
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
interface TrackedProperty {
|
| 30 |
+
value: any
|
| 31 |
+
children: Record<string, any>
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function trackProperties(
|
| 35 |
+
isImmutable: IsImmutableFunc,
|
| 36 |
+
ignoredPaths: IgnoredPaths = [],
|
| 37 |
+
obj: Record<string, any>,
|
| 38 |
+
path: string = '',
|
| 39 |
+
checkedObjects: Set<Record<string, any>> = new Set(),
|
| 40 |
+
) {
|
| 41 |
+
const tracked: Partial<TrackedProperty> = { value: obj }
|
| 42 |
+
|
| 43 |
+
if (!isImmutable(obj) && !checkedObjects.has(obj)) {
|
| 44 |
+
checkedObjects.add(obj)
|
| 45 |
+
tracked.children = {}
|
| 46 |
+
|
| 47 |
+
const hasIgnoredPaths = ignoredPaths.length > 0
|
| 48 |
+
|
| 49 |
+
for (const key in obj) {
|
| 50 |
+
const nestedPath = path ? path + '.' + key : key
|
| 51 |
+
|
| 52 |
+
if (hasIgnoredPaths) {
|
| 53 |
+
const hasMatches = ignoredPaths.some((ignored) => {
|
| 54 |
+
if (ignored instanceof RegExp) {
|
| 55 |
+
return ignored.test(nestedPath)
|
| 56 |
+
}
|
| 57 |
+
return nestedPath === ignored
|
| 58 |
+
})
|
| 59 |
+
if (hasMatches) {
|
| 60 |
+
continue
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
tracked.children[key] = trackProperties(
|
| 65 |
+
isImmutable,
|
| 66 |
+
ignoredPaths,
|
| 67 |
+
obj[key],
|
| 68 |
+
nestedPath,
|
| 69 |
+
)
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
return tracked as TrackedProperty
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
function detectMutations(
|
| 76 |
+
isImmutable: IsImmutableFunc,
|
| 77 |
+
ignoredPaths: IgnoredPaths = [],
|
| 78 |
+
trackedProperty: TrackedProperty,
|
| 79 |
+
obj: any,
|
| 80 |
+
sameParentRef: boolean = false,
|
| 81 |
+
path: string = '',
|
| 82 |
+
): { wasMutated: boolean; path?: string } {
|
| 83 |
+
const prevObj = trackedProperty ? trackedProperty.value : undefined
|
| 84 |
+
|
| 85 |
+
const sameRef = prevObj === obj
|
| 86 |
+
|
| 87 |
+
if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
|
| 88 |
+
return { wasMutated: true, path }
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
if (isImmutable(prevObj) || isImmutable(obj)) {
|
| 92 |
+
return { wasMutated: false }
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// Gather all keys from prev (tracked) and after objs
|
| 96 |
+
const keysToDetect: Record<string, boolean> = {}
|
| 97 |
+
for (let key in trackedProperty.children) {
|
| 98 |
+
keysToDetect[key] = true
|
| 99 |
+
}
|
| 100 |
+
for (let key in obj) {
|
| 101 |
+
keysToDetect[key] = true
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
const hasIgnoredPaths = ignoredPaths.length > 0
|
| 105 |
+
|
| 106 |
+
for (let key in keysToDetect) {
|
| 107 |
+
const nestedPath = path ? path + '.' + key : key
|
| 108 |
+
|
| 109 |
+
if (hasIgnoredPaths) {
|
| 110 |
+
const hasMatches = ignoredPaths.some((ignored) => {
|
| 111 |
+
if (ignored instanceof RegExp) {
|
| 112 |
+
return ignored.test(nestedPath)
|
| 113 |
+
}
|
| 114 |
+
return nestedPath === ignored
|
| 115 |
+
})
|
| 116 |
+
if (hasMatches) {
|
| 117 |
+
continue
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
const result = detectMutations(
|
| 122 |
+
isImmutable,
|
| 123 |
+
ignoredPaths,
|
| 124 |
+
trackedProperty.children[key],
|
| 125 |
+
obj[key],
|
| 126 |
+
sameRef,
|
| 127 |
+
nestedPath,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if (result.wasMutated) {
|
| 131 |
+
return result
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
return { wasMutated: false }
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
type IsImmutableFunc = (value: any) => boolean
|
| 138 |
+
|
| 139 |
+
/**
|
| 140 |
+
* Options for `createImmutableStateInvariantMiddleware()`.
|
| 141 |
+
*
|
| 142 |
+
* @public
|
| 143 |
+
*/
|
| 144 |
+
export interface ImmutableStateInvariantMiddlewareOptions {
|
| 145 |
+
/**
|
| 146 |
+
Callback function to check if a value is considered to be immutable.
|
| 147 |
+
This function is applied recursively to every value contained in the state.
|
| 148 |
+
The default implementation will return true for primitive types
|
| 149 |
+
(like numbers, strings, booleans, null and undefined).
|
| 150 |
+
*/
|
| 151 |
+
isImmutable?: IsImmutableFunc
|
| 152 |
+
/**
|
| 153 |
+
An array of dot-separated path strings that match named nodes from
|
| 154 |
+
the root state to ignore when checking for immutability.
|
| 155 |
+
Defaults to undefined
|
| 156 |
+
*/
|
| 157 |
+
ignoredPaths?: IgnoredPaths
|
| 158 |
+
/** Print a warning if checks take longer than N ms. Default: 32ms */
|
| 159 |
+
warnAfter?: number
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
/**
|
| 163 |
+
* Creates a middleware that checks whether any state was mutated in between
|
| 164 |
+
* dispatches or during a dispatch. If any mutations are detected, an error is
|
| 165 |
+
* thrown.
|
| 166 |
+
*
|
| 167 |
+
* @param options Middleware options.
|
| 168 |
+
*
|
| 169 |
+
* @public
|
| 170 |
+
*/
|
| 171 |
+
export function createImmutableStateInvariantMiddleware(
|
| 172 |
+
options: ImmutableStateInvariantMiddlewareOptions = {},
|
| 173 |
+
): Middleware {
|
| 174 |
+
if (process.env.NODE_ENV === 'production') {
|
| 175 |
+
return () => (next) => (action) => next(action)
|
| 176 |
+
} else {
|
| 177 |
+
function stringify(
|
| 178 |
+
obj: any,
|
| 179 |
+
serializer?: EntryProcessor,
|
| 180 |
+
indent?: string | number,
|
| 181 |
+
decycler?: EntryProcessor,
|
| 182 |
+
): string {
|
| 183 |
+
return JSON.stringify(obj, getSerialize(serializer, decycler), indent)
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
function getSerialize(
|
| 187 |
+
serializer?: EntryProcessor,
|
| 188 |
+
decycler?: EntryProcessor,
|
| 189 |
+
): EntryProcessor {
|
| 190 |
+
let stack: any[] = [],
|
| 191 |
+
keys: any[] = []
|
| 192 |
+
|
| 193 |
+
if (!decycler)
|
| 194 |
+
decycler = function (_: string, value: any) {
|
| 195 |
+
if (stack[0] === value) return '[Circular ~]'
|
| 196 |
+
return (
|
| 197 |
+
'[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
|
| 198 |
+
)
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
return function (this: any, key: string, value: any) {
|
| 202 |
+
if (stack.length > 0) {
|
| 203 |
+
var thisPos = stack.indexOf(this)
|
| 204 |
+
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
|
| 205 |
+
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
|
| 206 |
+
if (~stack.indexOf(value)) value = decycler!.call(this, key, value)
|
| 207 |
+
} else stack.push(value)
|
| 208 |
+
|
| 209 |
+
return serializer == null ? value : serializer.call(this, key, value)
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
let {
|
| 214 |
+
isImmutable = isImmutableDefault,
|
| 215 |
+
ignoredPaths,
|
| 216 |
+
warnAfter = 32,
|
| 217 |
+
} = options
|
| 218 |
+
|
| 219 |
+
const track = trackForMutations.bind(null, isImmutable, ignoredPaths)
|
| 220 |
+
|
| 221 |
+
return ({ getState }) => {
|
| 222 |
+
let state = getState()
|
| 223 |
+
let tracker = track(state)
|
| 224 |
+
|
| 225 |
+
let result
|
| 226 |
+
return (next) => (action) => {
|
| 227 |
+
const measureUtils = getTimeMeasureUtils(
|
| 228 |
+
warnAfter,
|
| 229 |
+
'ImmutableStateInvariantMiddleware',
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
measureUtils.measureTime(() => {
|
| 233 |
+
state = getState()
|
| 234 |
+
|
| 235 |
+
result = tracker.detectMutations()
|
| 236 |
+
// Track before potentially not meeting the invariant
|
| 237 |
+
tracker = track(state)
|
| 238 |
+
|
| 239 |
+
if (result.wasMutated) {
|
| 240 |
+
throw new Error(
|
| 241 |
+
`A state mutation was detected between dispatches, in the path '${
|
| 242 |
+
result.path || ''
|
| 243 |
+
}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
|
| 244 |
+
)
|
| 245 |
+
}
|
| 246 |
+
})
|
| 247 |
+
|
| 248 |
+
const dispatchedAction = next(action)
|
| 249 |
+
|
| 250 |
+
measureUtils.measureTime(() => {
|
| 251 |
+
state = getState()
|
| 252 |
+
|
| 253 |
+
result = tracker.detectMutations()
|
| 254 |
+
// Track before potentially not meeting the invariant
|
| 255 |
+
tracker = track(state)
|
| 256 |
+
|
| 257 |
+
if (result.wasMutated) {
|
| 258 |
+
throw new Error(
|
| 259 |
+
`A state mutation was detected inside a dispatch, in the path: ${
|
| 260 |
+
result.path || ''
|
| 261 |
+
}. Take a look at the reducer(s) handling the action ${stringify(
|
| 262 |
+
action,
|
| 263 |
+
)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,
|
| 264 |
+
)
|
| 265 |
+
}
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// This must remain here so that the `mangleErrors.cjs` build script
|
| 2 |
+
// does not have to import this into each source file it rewrites.
|
| 3 |
+
import { formatProdErrorMessage } from './formatProdErrorMessage'
|
| 4 |
+
|
| 5 |
+
export * from 'redux'
|
| 6 |
+
export { freeze, original } from 'immer'
|
| 7 |
+
export { createNextState, current, isDraft } from './immerImports'
|
| 8 |
+
export type { Draft, WritableDraft } from 'immer'
|
| 9 |
+
export { createSelector, lruMemoize } from 'reselect'
|
| 10 |
+
export { createSelectorCreator, weakMapMemoize } from './reselectImports'
|
| 11 |
+
export type { Selector, OutputSelector } from 'reselect'
|
| 12 |
+
export {
|
| 13 |
+
createDraftSafeSelector,
|
| 14 |
+
createDraftSafeSelectorCreator,
|
| 15 |
+
} from './createDraftSafeSelector'
|
| 16 |
+
export type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'
|
| 17 |
+
|
| 18 |
+
export {
|
| 19 |
+
// js
|
| 20 |
+
configureStore,
|
| 21 |
+
} from './configureStore'
|
| 22 |
+
export type {
|
| 23 |
+
// types
|
| 24 |
+
ConfigureStoreOptions,
|
| 25 |
+
EnhancedStore,
|
| 26 |
+
} from './configureStore'
|
| 27 |
+
export type { DevToolsEnhancerOptions } from './devtoolsExtension'
|
| 28 |
+
export {
|
| 29 |
+
// js
|
| 30 |
+
createAction,
|
| 31 |
+
isActionCreator,
|
| 32 |
+
isFSA as isFluxStandardAction,
|
| 33 |
+
} from './createAction'
|
| 34 |
+
export type {
|
| 35 |
+
// types
|
| 36 |
+
PayloadAction,
|
| 37 |
+
PayloadActionCreator,
|
| 38 |
+
ActionCreatorWithNonInferrablePayload,
|
| 39 |
+
ActionCreatorWithOptionalPayload,
|
| 40 |
+
ActionCreatorWithPayload,
|
| 41 |
+
ActionCreatorWithoutPayload,
|
| 42 |
+
ActionCreatorWithPreparedPayload,
|
| 43 |
+
PrepareAction,
|
| 44 |
+
} from './createAction'
|
| 45 |
+
export {
|
| 46 |
+
// js
|
| 47 |
+
createReducer,
|
| 48 |
+
} from './createReducer'
|
| 49 |
+
export type {
|
| 50 |
+
// types
|
| 51 |
+
Actions,
|
| 52 |
+
CaseReducer,
|
| 53 |
+
CaseReducers,
|
| 54 |
+
} from './createReducer'
|
| 55 |
+
export {
|
| 56 |
+
// js
|
| 57 |
+
createSlice,
|
| 58 |
+
buildCreateSlice,
|
| 59 |
+
asyncThunkCreator,
|
| 60 |
+
ReducerType,
|
| 61 |
+
} from './createSlice'
|
| 62 |
+
|
| 63 |
+
export type {
|
| 64 |
+
// types
|
| 65 |
+
CreateSliceOptions,
|
| 66 |
+
Slice,
|
| 67 |
+
CaseReducerActions,
|
| 68 |
+
SliceCaseReducers,
|
| 69 |
+
ValidateSliceCaseReducers,
|
| 70 |
+
CaseReducerWithPrepare,
|
| 71 |
+
ReducerCreators,
|
| 72 |
+
SliceSelectors,
|
| 73 |
+
} from './createSlice'
|
| 74 |
+
export type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'
|
| 75 |
+
export { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'
|
| 76 |
+
export {
|
| 77 |
+
// js
|
| 78 |
+
createImmutableStateInvariantMiddleware,
|
| 79 |
+
isImmutableDefault,
|
| 80 |
+
} from './immutableStateInvariantMiddleware'
|
| 81 |
+
export type {
|
| 82 |
+
// types
|
| 83 |
+
ImmutableStateInvariantMiddlewareOptions,
|
| 84 |
+
} from './immutableStateInvariantMiddleware'
|
| 85 |
+
export {
|
| 86 |
+
// js
|
| 87 |
+
createSerializableStateInvariantMiddleware,
|
| 88 |
+
findNonSerializableValue,
|
| 89 |
+
isPlain,
|
| 90 |
+
} from './serializableStateInvariantMiddleware'
|
| 91 |
+
export type {
|
| 92 |
+
// types
|
| 93 |
+
SerializableStateInvariantMiddlewareOptions,
|
| 94 |
+
} from './serializableStateInvariantMiddleware'
|
| 95 |
+
export type {
|
| 96 |
+
// types
|
| 97 |
+
ActionReducerMapBuilder,
|
| 98 |
+
AsyncThunkReducers,
|
| 99 |
+
} from './mapBuilders'
|
| 100 |
+
export { Tuple } from './utils'
|
| 101 |
+
|
| 102 |
+
export { createEntityAdapter } from './entities/create_adapter'
|
| 103 |
+
export type {
|
| 104 |
+
EntityState,
|
| 105 |
+
EntityAdapter,
|
| 106 |
+
EntitySelectors,
|
| 107 |
+
EntityStateAdapter,
|
| 108 |
+
EntityId,
|
| 109 |
+
Update,
|
| 110 |
+
IdSelector,
|
| 111 |
+
Comparer,
|
| 112 |
+
} from './entities/models'
|
| 113 |
+
|
| 114 |
+
export {
|
| 115 |
+
createAsyncThunk,
|
| 116 |
+
unwrapResult,
|
| 117 |
+
miniSerializeError,
|
| 118 |
+
} from './createAsyncThunk'
|
| 119 |
+
export type {
|
| 120 |
+
AsyncThunk,
|
| 121 |
+
AsyncThunkConfig,
|
| 122 |
+
AsyncThunkDispatchConfig,
|
| 123 |
+
AsyncThunkOptions,
|
| 124 |
+
AsyncThunkAction,
|
| 125 |
+
AsyncThunkPayloadCreatorReturnValue,
|
| 126 |
+
AsyncThunkPayloadCreator,
|
| 127 |
+
GetState,
|
| 128 |
+
GetThunkAPI,
|
| 129 |
+
SerializedError,
|
| 130 |
+
CreateAsyncThunkFunction,
|
| 131 |
+
} from './createAsyncThunk'
|
| 132 |
+
|
| 133 |
+
export {
|
| 134 |
+
// js
|
| 135 |
+
isAllOf,
|
| 136 |
+
isAnyOf,
|
| 137 |
+
isPending,
|
| 138 |
+
isRejected,
|
| 139 |
+
isFulfilled,
|
| 140 |
+
isAsyncThunkAction,
|
| 141 |
+
isRejectedWithValue,
|
| 142 |
+
} from './matchers'
|
| 143 |
+
export type {
|
| 144 |
+
// types
|
| 145 |
+
ActionMatchingAllOf,
|
| 146 |
+
ActionMatchingAnyOf,
|
| 147 |
+
} from './matchers'
|
| 148 |
+
|
| 149 |
+
export { nanoid } from './nanoid'
|
| 150 |
+
|
| 151 |
+
export type {
|
| 152 |
+
ListenerEffect,
|
| 153 |
+
ListenerMiddleware,
|
| 154 |
+
ListenerEffectAPI,
|
| 155 |
+
ListenerMiddlewareInstance,
|
| 156 |
+
CreateListenerMiddlewareOptions,
|
| 157 |
+
ListenerErrorHandler,
|
| 158 |
+
TypedStartListening,
|
| 159 |
+
TypedAddListener,
|
| 160 |
+
TypedStopListening,
|
| 161 |
+
TypedRemoveListener,
|
| 162 |
+
UnsubscribeListener,
|
| 163 |
+
UnsubscribeListenerOptions,
|
| 164 |
+
ForkedTaskExecutor,
|
| 165 |
+
ForkedTask,
|
| 166 |
+
ForkedTaskAPI,
|
| 167 |
+
AsyncTaskExecutor,
|
| 168 |
+
SyncTaskExecutor,
|
| 169 |
+
TaskCancelled,
|
| 170 |
+
TaskRejected,
|
| 171 |
+
TaskResolved,
|
| 172 |
+
TaskResult,
|
| 173 |
+
} from './listenerMiddleware/index'
|
| 174 |
+
export type { AnyListenerPredicate } from './listenerMiddleware/types'
|
| 175 |
+
|
| 176 |
+
export {
|
| 177 |
+
createListenerMiddleware,
|
| 178 |
+
addListener,
|
| 179 |
+
removeListener,
|
| 180 |
+
clearAllListeners,
|
| 181 |
+
TaskAbortError,
|
| 182 |
+
} from './listenerMiddleware/index'
|
| 183 |
+
|
| 184 |
+
export type {
|
| 185 |
+
AddMiddleware,
|
| 186 |
+
DynamicDispatch,
|
| 187 |
+
DynamicMiddlewareInstance,
|
| 188 |
+
GetDispatchType as GetDispatch,
|
| 189 |
+
MiddlewareApiConfig,
|
| 190 |
+
} from './dynamicMiddleware/types'
|
| 191 |
+
export { createDynamicMiddleware } from './dynamicMiddleware/index'
|
| 192 |
+
|
| 193 |
+
export {
|
| 194 |
+
SHOULD_AUTOBATCH,
|
| 195 |
+
prepareAutoBatched,
|
| 196 |
+
autoBatchEnhancer,
|
| 197 |
+
} from './autoBatchEnhancer'
|
| 198 |
+
export type { AutoBatchOptions } from './autoBatchEnhancer'
|
| 199 |
+
|
| 200 |
+
export { combineSlices } from './combineSlices'
|
| 201 |
+
|
| 202 |
+
export type {
|
| 203 |
+
CombinedSliceReducer,
|
| 204 |
+
WithSlice,
|
| 205 |
+
WithSlicePreloadedState,
|
| 206 |
+
} from './combineSlices'
|
| 207 |
+
|
| 208 |
+
export type {
|
| 209 |
+
ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions,
|
| 210 |
+
SafePromise,
|
| 211 |
+
} from './tsHelpers'
|
| 212 |
+
|
| 213 |
+
export { formatProdErrorMessage } from './formatProdErrorMessage'
|
node_modules/@reduxjs/toolkit/src/listenerMiddleware/exceptions.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { SerializedError } from '@reduxjs/toolkit'
|
| 2 |
+
|
| 3 |
+
const task = 'task'
|
| 4 |
+
const listener = 'listener'
|
| 5 |
+
const completed = 'completed'
|
| 6 |
+
const cancelled = 'cancelled'
|
| 7 |
+
|
| 8 |
+
/* TaskAbortError error codes */
|
| 9 |
+
export const taskCancelled = `task-${cancelled}` as const
|
| 10 |
+
export const taskCompleted = `task-${completed}` as const
|
| 11 |
+
export const listenerCancelled = `${listener}-${cancelled}` as const
|
| 12 |
+
export const listenerCompleted = `${listener}-${completed}` as const
|
| 13 |
+
|
| 14 |
+
export class TaskAbortError implements SerializedError {
|
| 15 |
+
name = 'TaskAbortError'
|
| 16 |
+
message: string
|
| 17 |
+
constructor(public code: string | undefined) {
|
| 18 |
+
this.message = `${task} ${cancelled} (reason: ${code})`
|
| 19 |
+
}
|
| 20 |
+
}
|
node_modules/@reduxjs/toolkit/src/listenerMiddleware/index.ts
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'
|
| 2 |
+
import { isAction } from '../reduxImports'
|
| 3 |
+
import type { ThunkDispatch } from 'redux-thunk'
|
| 4 |
+
import { createAction } from '../createAction'
|
| 5 |
+
import { nanoid } from '../nanoid'
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
TaskAbortError,
|
| 9 |
+
listenerCancelled,
|
| 10 |
+
listenerCompleted,
|
| 11 |
+
taskCancelled,
|
| 12 |
+
taskCompleted,
|
| 13 |
+
} from './exceptions'
|
| 14 |
+
import {
|
| 15 |
+
createDelay,
|
| 16 |
+
createPause,
|
| 17 |
+
raceWithSignal,
|
| 18 |
+
runTask,
|
| 19 |
+
validateActive,
|
| 20 |
+
} from './task'
|
| 21 |
+
import type {
|
| 22 |
+
AddListenerOverloads,
|
| 23 |
+
AnyListenerPredicate,
|
| 24 |
+
CreateListenerMiddlewareOptions,
|
| 25 |
+
FallbackAddListenerOptions,
|
| 26 |
+
ForkOptions,
|
| 27 |
+
ForkedTask,
|
| 28 |
+
ForkedTaskExecutor,
|
| 29 |
+
ListenerEntry,
|
| 30 |
+
ListenerErrorHandler,
|
| 31 |
+
ListenerErrorInfo,
|
| 32 |
+
ListenerMiddleware,
|
| 33 |
+
ListenerMiddlewareInstance,
|
| 34 |
+
TakePattern,
|
| 35 |
+
TaskResult,
|
| 36 |
+
TypedAddListener,
|
| 37 |
+
TypedCreateListenerEntry,
|
| 38 |
+
TypedRemoveListener,
|
| 39 |
+
UnsubscribeListener,
|
| 40 |
+
UnsubscribeListenerOptions,
|
| 41 |
+
} from './types'
|
| 42 |
+
import {
|
| 43 |
+
addAbortSignalListener,
|
| 44 |
+
assertFunction,
|
| 45 |
+
catchRejection,
|
| 46 |
+
noop,
|
| 47 |
+
} from './utils'
|
| 48 |
+
export { TaskAbortError } from './exceptions'
|
| 49 |
+
export type {
|
| 50 |
+
AsyncTaskExecutor,
|
| 51 |
+
CreateListenerMiddlewareOptions,
|
| 52 |
+
ForkedTask,
|
| 53 |
+
ForkedTaskAPI,
|
| 54 |
+
ForkedTaskExecutor,
|
| 55 |
+
ListenerEffect,
|
| 56 |
+
ListenerEffectAPI,
|
| 57 |
+
ListenerErrorHandler,
|
| 58 |
+
ListenerMiddleware,
|
| 59 |
+
ListenerMiddlewareInstance,
|
| 60 |
+
SyncTaskExecutor,
|
| 61 |
+
TaskCancelled,
|
| 62 |
+
TaskRejected,
|
| 63 |
+
TaskResolved,
|
| 64 |
+
TaskResult,
|
| 65 |
+
TypedAddListener,
|
| 66 |
+
TypedRemoveListener,
|
| 67 |
+
TypedStartListening,
|
| 68 |
+
TypedStopListening,
|
| 69 |
+
UnsubscribeListener,
|
| 70 |
+
UnsubscribeListenerOptions,
|
| 71 |
+
} from './types'
|
| 72 |
+
|
| 73 |
+
//Overly-aggressive byte-shaving
|
| 74 |
+
const { assign } = Object
|
| 75 |
+
/**
|
| 76 |
+
* @internal
|
| 77 |
+
*/
|
| 78 |
+
const INTERNAL_NIL_TOKEN = {} as const
|
| 79 |
+
|
| 80 |
+
const alm = 'listenerMiddleware' as const
|
| 81 |
+
|
| 82 |
+
const createFork = (
|
| 83 |
+
parentAbortSignal: AbortSignal,
|
| 84 |
+
parentBlockingPromises: Promise<any>[],
|
| 85 |
+
) => {
|
| 86 |
+
const linkControllers = (controller: AbortController) =>
|
| 87 |
+
addAbortSignalListener(parentAbortSignal, () =>
|
| 88 |
+
controller.abort(parentAbortSignal.reason),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
return <T>(
|
| 92 |
+
taskExecutor: ForkedTaskExecutor<T>,
|
| 93 |
+
opts?: ForkOptions,
|
| 94 |
+
): ForkedTask<T> => {
|
| 95 |
+
assertFunction(taskExecutor, 'taskExecutor')
|
| 96 |
+
const childAbortController = new AbortController()
|
| 97 |
+
|
| 98 |
+
linkControllers(childAbortController)
|
| 99 |
+
|
| 100 |
+
const result = runTask<T>(
|
| 101 |
+
async (): Promise<T> => {
|
| 102 |
+
validateActive(parentAbortSignal)
|
| 103 |
+
validateActive(childAbortController.signal)
|
| 104 |
+
const result = (await taskExecutor({
|
| 105 |
+
pause: createPause(childAbortController.signal),
|
| 106 |
+
delay: createDelay(childAbortController.signal),
|
| 107 |
+
signal: childAbortController.signal,
|
| 108 |
+
})) as T
|
| 109 |
+
validateActive(childAbortController.signal)
|
| 110 |
+
return result
|
| 111 |
+
},
|
| 112 |
+
() => childAbortController.abort(taskCompleted),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
if (opts?.autoJoin) {
|
| 116 |
+
parentBlockingPromises.push(result.catch(noop))
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
result: createPause<TaskResult<T>>(parentAbortSignal)(result),
|
| 121 |
+
cancel() {
|
| 122 |
+
childAbortController.abort(taskCancelled)
|
| 123 |
+
},
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
const createTakePattern = <S>(
|
| 129 |
+
startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>,
|
| 130 |
+
signal: AbortSignal,
|
| 131 |
+
): TakePattern<S> => {
|
| 132 |
+
/**
|
| 133 |
+
* A function that takes a ListenerPredicate and an optional timeout,
|
| 134 |
+
* and resolves when either the predicate returns `true` based on an action
|
| 135 |
+
* state combination or when the timeout expires.
|
| 136 |
+
* If the parent listener is canceled while waiting, this will throw a
|
| 137 |
+
* TaskAbortError.
|
| 138 |
+
*/
|
| 139 |
+
const take = async <P extends AnyListenerPredicate<S>>(
|
| 140 |
+
predicate: P,
|
| 141 |
+
timeout: number | undefined,
|
| 142 |
+
) => {
|
| 143 |
+
validateActive(signal)
|
| 144 |
+
|
| 145 |
+
// Placeholder unsubscribe function until the listener is added
|
| 146 |
+
let unsubscribe: UnsubscribeListener = () => {}
|
| 147 |
+
|
| 148 |
+
const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {
|
| 149 |
+
// Inside the Promise, we synchronously add the listener.
|
| 150 |
+
let stopListening = startListening({
|
| 151 |
+
predicate: predicate as any,
|
| 152 |
+
effect: (action, listenerApi): void => {
|
| 153 |
+
// One-shot listener that cleans up as soon as the predicate passes
|
| 154 |
+
listenerApi.unsubscribe()
|
| 155 |
+
// Resolve the promise with the same arguments the predicate saw
|
| 156 |
+
resolve([
|
| 157 |
+
action,
|
| 158 |
+
listenerApi.getState(),
|
| 159 |
+
listenerApi.getOriginalState(),
|
| 160 |
+
])
|
| 161 |
+
},
|
| 162 |
+
})
|
| 163 |
+
unsubscribe = () => {
|
| 164 |
+
stopListening()
|
| 165 |
+
reject()
|
| 166 |
+
}
|
| 167 |
+
})
|
| 168 |
+
|
| 169 |
+
const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise]
|
| 170 |
+
|
| 171 |
+
if (timeout != null) {
|
| 172 |
+
promises.push(
|
| 173 |
+
new Promise<null>((resolve) => setTimeout(resolve, timeout, null)),
|
| 174 |
+
)
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
try {
|
| 178 |
+
const output = await raceWithSignal(signal, Promise.race(promises))
|
| 179 |
+
|
| 180 |
+
validateActive(signal)
|
| 181 |
+
return output
|
| 182 |
+
} finally {
|
| 183 |
+
// Always clean up the listener
|
| 184 |
+
unsubscribe()
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) =>
|
| 189 |
+
catchRejection(take(predicate, timeout))) as TakePattern<S>
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
const getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {
|
| 193 |
+
let { type, actionCreator, matcher, predicate, effect } = options
|
| 194 |
+
|
| 195 |
+
if (type) {
|
| 196 |
+
predicate = createAction(type).match
|
| 197 |
+
} else if (actionCreator) {
|
| 198 |
+
type = actionCreator!.type
|
| 199 |
+
predicate = actionCreator.match
|
| 200 |
+
} else if (matcher) {
|
| 201 |
+
predicate = matcher
|
| 202 |
+
} else if (predicate) {
|
| 203 |
+
// pass
|
| 204 |
+
} else {
|
| 205 |
+
throw new Error(
|
| 206 |
+
'Creating or removing a listener requires one of the known fields for matching an action',
|
| 207 |
+
)
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
assertFunction(effect, 'options.listener')
|
| 211 |
+
|
| 212 |
+
return { predicate, type, effect }
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
/** Accepts the possible options for creating a listener, and returns a formatted listener entry */
|
| 216 |
+
export const createListenerEntry: TypedCreateListenerEntry<unknown> =
|
| 217 |
+
/* @__PURE__ */ assign(
|
| 218 |
+
(options: FallbackAddListenerOptions) => {
|
| 219 |
+
const { type, predicate, effect } = getListenerEntryPropsFrom(options)
|
| 220 |
+
|
| 221 |
+
const entry: ListenerEntry<unknown> = {
|
| 222 |
+
id: nanoid(),
|
| 223 |
+
effect,
|
| 224 |
+
type,
|
| 225 |
+
predicate,
|
| 226 |
+
pending: new Set<AbortController>(),
|
| 227 |
+
unsubscribe: () => {
|
| 228 |
+
throw new Error('Unsubscribe not initialized')
|
| 229 |
+
},
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
return entry
|
| 233 |
+
},
|
| 234 |
+
{ withTypes: () => createListenerEntry },
|
| 235 |
+
) as unknown as TypedCreateListenerEntry<unknown>
|
| 236 |
+
|
| 237 |
+
const findListenerEntry = (
|
| 238 |
+
listenerMap: Map<string, ListenerEntry>,
|
| 239 |
+
options: FallbackAddListenerOptions,
|
| 240 |
+
) => {
|
| 241 |
+
const { type, effect, predicate } = getListenerEntryPropsFrom(options)
|
| 242 |
+
|
| 243 |
+
return Array.from(listenerMap.values()).find((entry) => {
|
| 244 |
+
const matchPredicateOrType =
|
| 245 |
+
typeof type === 'string'
|
| 246 |
+
? entry.type === type
|
| 247 |
+
: entry.predicate === predicate
|
| 248 |
+
|
| 249 |
+
return matchPredicateOrType && entry.effect === effect
|
| 250 |
+
})
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
const cancelActiveListeners = (
|
| 254 |
+
entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
|
| 255 |
+
) => {
|
| 256 |
+
entry.pending.forEach((controller) => {
|
| 257 |
+
controller.abort(listenerCancelled)
|
| 258 |
+
})
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
const createClearListenerMiddleware = (
|
| 262 |
+
listenerMap: Map<string, ListenerEntry>,
|
| 263 |
+
executingListeners: Map<ListenerEntry, number>,
|
| 264 |
+
) => {
|
| 265 |
+
return () => {
|
| 266 |
+
for (const listener of executingListeners.keys()) {
|
| 267 |
+
cancelActiveListeners(listener)
|
| 268 |
+
}
|
| 269 |
+
listenerMap.clear()
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
/**
|
| 274 |
+
* Safely reports errors to the `errorHandler` provided.
|
| 275 |
+
* Errors that occur inside `errorHandler` are notified in a new task.
|
| 276 |
+
* Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)
|
| 277 |
+
* @param errorHandler
|
| 278 |
+
* @param errorToNotify
|
| 279 |
+
*/
|
| 280 |
+
const safelyNotifyError = (
|
| 281 |
+
errorHandler: ListenerErrorHandler,
|
| 282 |
+
errorToNotify: unknown,
|
| 283 |
+
errorInfo: ListenerErrorInfo,
|
| 284 |
+
): void => {
|
| 285 |
+
try {
|
| 286 |
+
errorHandler(errorToNotify, errorInfo)
|
| 287 |
+
} catch (errorHandlerError) {
|
| 288 |
+
// We cannot let an error raised here block the listener queue.
|
| 289 |
+
// The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...
|
| 290 |
+
setTimeout(() => {
|
| 291 |
+
throw errorHandlerError
|
| 292 |
+
}, 0)
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
/**
|
| 297 |
+
* @public
|
| 298 |
+
*/
|
| 299 |
+
export const addListener = /* @__PURE__ */ assign(
|
| 300 |
+
/* @__PURE__ */ createAction(`${alm}/add`),
|
| 301 |
+
{
|
| 302 |
+
withTypes: () => addListener,
|
| 303 |
+
},
|
| 304 |
+
) as unknown as TypedAddListener<unknown>
|
| 305 |
+
|
| 306 |
+
/**
|
| 307 |
+
* @public
|
| 308 |
+
*/
|
| 309 |
+
export const clearAllListeners = /* @__PURE__ */ createAction(
|
| 310 |
+
`${alm}/removeAll`,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
/**
|
| 314 |
+
* @public
|
| 315 |
+
*/
|
| 316 |
+
export const removeListener = /* @__PURE__ */ assign(
|
| 317 |
+
/* @__PURE__ */ createAction(`${alm}/remove`),
|
| 318 |
+
{
|
| 319 |
+
withTypes: () => removeListener,
|
| 320 |
+
},
|
| 321 |
+
) as unknown as TypedRemoveListener<unknown>
|
| 322 |
+
|
| 323 |
+
const defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {
|
| 324 |
+
console.error(`${alm}/error`, ...args)
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
/**
|
| 328 |
+
* @public
|
| 329 |
+
*/
|
| 330 |
+
export const createListenerMiddleware = <
|
| 331 |
+
StateType = unknown,
|
| 332 |
+
DispatchType extends Dispatch<Action> = ThunkDispatch<
|
| 333 |
+
StateType,
|
| 334 |
+
unknown,
|
| 335 |
+
UnknownAction
|
| 336 |
+
>,
|
| 337 |
+
ExtraArgument = unknown,
|
| 338 |
+
>(
|
| 339 |
+
middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},
|
| 340 |
+
) => {
|
| 341 |
+
const listenerMap = new Map<string, ListenerEntry>()
|
| 342 |
+
|
| 343 |
+
// Track listeners whose effect is currently executing so clearListeners can
|
| 344 |
+
// abort even listeners that have become unsubscribed while executing.
|
| 345 |
+
const executingListeners = new Map<ListenerEntry, number>()
|
| 346 |
+
const trackExecutingListener = (entry: ListenerEntry) => {
|
| 347 |
+
const count = executingListeners.get(entry) ?? 0
|
| 348 |
+
executingListeners.set(entry, count + 1)
|
| 349 |
+
}
|
| 350 |
+
const untrackExecutingListener = (entry: ListenerEntry) => {
|
| 351 |
+
const count = executingListeners.get(entry) ?? 1
|
| 352 |
+
if (count === 1) {
|
| 353 |
+
executingListeners.delete(entry)
|
| 354 |
+
} else {
|
| 355 |
+
executingListeners.set(entry, count - 1)
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
const { extra, onError = defaultErrorHandler } = middlewareOptions
|
| 360 |
+
|
| 361 |
+
assertFunction(onError, 'onError')
|
| 362 |
+
|
| 363 |
+
const insertEntry = (entry: ListenerEntry) => {
|
| 364 |
+
entry.unsubscribe = () => listenerMap.delete(entry.id)
|
| 365 |
+
|
| 366 |
+
listenerMap.set(entry.id, entry)
|
| 367 |
+
return (cancelOptions?: UnsubscribeListenerOptions) => {
|
| 368 |
+
entry.unsubscribe()
|
| 369 |
+
if (cancelOptions?.cancelActive) {
|
| 370 |
+
cancelActiveListeners(entry)
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
const startListening = ((options: FallbackAddListenerOptions) => {
|
| 376 |
+
const entry =
|
| 377 |
+
findListenerEntry(listenerMap, options) ??
|
| 378 |
+
createListenerEntry(options as any)
|
| 379 |
+
|
| 380 |
+
return insertEntry(entry)
|
| 381 |
+
}) as AddListenerOverloads<any>
|
| 382 |
+
|
| 383 |
+
assign(startListening, {
|
| 384 |
+
withTypes: () => startListening,
|
| 385 |
+
})
|
| 386 |
+
|
| 387 |
+
const stopListening = (
|
| 388 |
+
options: FallbackAddListenerOptions & UnsubscribeListenerOptions,
|
| 389 |
+
): boolean => {
|
| 390 |
+
const entry = findListenerEntry(listenerMap, options)
|
| 391 |
+
|
| 392 |
+
if (entry) {
|
| 393 |
+
entry.unsubscribe()
|
| 394 |
+
if (options.cancelActive) {
|
| 395 |
+
cancelActiveListeners(entry)
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
return !!entry
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
assign(stopListening, {
|
| 403 |
+
withTypes: () => stopListening,
|
| 404 |
+
})
|
| 405 |
+
|
| 406 |
+
const notifyListener = async (
|
| 407 |
+
entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,
|
| 408 |
+
action: unknown,
|
| 409 |
+
api: MiddlewareAPI,
|
| 410 |
+
getOriginalState: () => StateType,
|
| 411 |
+
) => {
|
| 412 |
+
const internalTaskController = new AbortController()
|
| 413 |
+
const take = createTakePattern(
|
| 414 |
+
startListening as AddListenerOverloads<any>,
|
| 415 |
+
internalTaskController.signal,
|
| 416 |
+
)
|
| 417 |
+
const autoJoinPromises: Promise<any>[] = []
|
| 418 |
+
|
| 419 |
+
try {
|
| 420 |
+
entry.pending.add(internalTaskController)
|
| 421 |
+
trackExecutingListener(entry)
|
| 422 |
+
await Promise.resolve(
|
| 423 |
+
entry.effect(
|
| 424 |
+
action,
|
| 425 |
+
// Use assign() rather than ... to avoid extra helper functions added to bundle
|
| 426 |
+
assign({}, api, {
|
| 427 |
+
getOriginalState,
|
| 428 |
+
condition: (
|
| 429 |
+
predicate: AnyListenerPredicate<any>,
|
| 430 |
+
timeout?: number,
|
| 431 |
+
) => take(predicate, timeout).then(Boolean),
|
| 432 |
+
take,
|
| 433 |
+
delay: createDelay(internalTaskController.signal),
|
| 434 |
+
pause: createPause<any>(internalTaskController.signal),
|
| 435 |
+
extra,
|
| 436 |
+
signal: internalTaskController.signal,
|
| 437 |
+
fork: createFork(internalTaskController.signal, autoJoinPromises),
|
| 438 |
+
unsubscribe: entry.unsubscribe,
|
| 439 |
+
subscribe: () => {
|
| 440 |
+
listenerMap.set(entry.id, entry)
|
| 441 |
+
},
|
| 442 |
+
cancelActiveListeners: () => {
|
| 443 |
+
entry.pending.forEach((controller, _, set) => {
|
| 444 |
+
if (controller !== internalTaskController) {
|
| 445 |
+
controller.abort(listenerCancelled)
|
| 446 |
+
set.delete(controller)
|
| 447 |
+
}
|
| 448 |
+
})
|
| 449 |
+
},
|
| 450 |
+
cancel: () => {
|
| 451 |
+
internalTaskController.abort(listenerCancelled)
|
| 452 |
+
entry.pending.delete(internalTaskController)
|
| 453 |
+
},
|
| 454 |
+
throwIfCancelled: () => {
|
| 455 |
+
validateActive(internalTaskController.signal)
|
| 456 |
+
},
|
| 457 |
+
}),
|
| 458 |
+
),
|
| 459 |
+
)
|
| 460 |
+
} catch (listenerError) {
|
| 461 |
+
if (!(listenerError instanceof TaskAbortError)) {
|
| 462 |
+
safelyNotifyError(onError, listenerError, {
|
| 463 |
+
raisedBy: 'effect',
|
| 464 |
+
})
|
| 465 |
+
}
|
| 466 |
+
} finally {
|
| 467 |
+
await Promise.all(autoJoinPromises)
|
| 468 |
+
|
| 469 |
+
internalTaskController.abort(listenerCompleted) // Notify that the task has completed
|
| 470 |
+
untrackExecutingListener(entry)
|
| 471 |
+
entry.pending.delete(internalTaskController)
|
| 472 |
+
}
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
const clearListenerMiddleware = createClearListenerMiddleware(
|
| 476 |
+
listenerMap,
|
| 477 |
+
executingListeners,
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
const middleware: ListenerMiddleware<
|
| 481 |
+
StateType,
|
| 482 |
+
DispatchType,
|
| 483 |
+
ExtraArgument
|
| 484 |
+
> = (api) => (next) => (action) => {
|
| 485 |
+
if (!isAction(action)) {
|
| 486 |
+
// we only want to notify listeners for action objects
|
| 487 |
+
return next(action)
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
if (addListener.match(action)) {
|
| 491 |
+
return startListening(action.payload as any)
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
if (clearAllListeners.match(action)) {
|
| 495 |
+
clearListenerMiddleware()
|
| 496 |
+
return
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
if (removeListener.match(action)) {
|
| 500 |
+
return stopListening(action.payload)
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
// Need to get this state _before_ the reducer processes the action
|
| 504 |
+
let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState()
|
| 505 |
+
|
| 506 |
+
// `getOriginalState` can only be called synchronously.
|
| 507 |
+
// @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820
|
| 508 |
+
const getOriginalState = (): StateType => {
|
| 509 |
+
if (originalState === INTERNAL_NIL_TOKEN) {
|
| 510 |
+
throw new Error(
|
| 511 |
+
`${alm}: getOriginalState can only be called synchronously`,
|
| 512 |
+
)
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
return originalState as StateType
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
let result: unknown
|
| 519 |
+
|
| 520 |
+
try {
|
| 521 |
+
// Actually forward the action to the reducer before we handle listeners
|
| 522 |
+
result = next(action)
|
| 523 |
+
|
| 524 |
+
if (listenerMap.size > 0) {
|
| 525 |
+
const currentState = api.getState()
|
| 526 |
+
// Work around ESBuild+TS transpilation issue
|
| 527 |
+
const listenerEntries = Array.from(listenerMap.values())
|
| 528 |
+
for (const entry of listenerEntries) {
|
| 529 |
+
let runListener = false
|
| 530 |
+
|
| 531 |
+
try {
|
| 532 |
+
runListener = entry.predicate(action, currentState, originalState)
|
| 533 |
+
} catch (predicateError) {
|
| 534 |
+
runListener = false
|
| 535 |
+
|
| 536 |
+
safelyNotifyError(onError, predicateError, {
|
| 537 |
+
raisedBy: 'predicate',
|
| 538 |
+
})
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
if (!runListener) {
|
| 542 |
+
continue
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
notifyListener(entry, action, api, getOriginalState)
|
| 546 |
+
}
|
| 547 |
+
}
|
| 548 |
+
} finally {
|
| 549 |
+
// Remove `originalState` store from this scope.
|
| 550 |
+
originalState = INTERNAL_NIL_TOKEN
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
return result
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
return {
|
| 557 |
+
middleware,
|
| 558 |
+
startListening,
|
| 559 |
+
stopListening,
|
| 560 |
+
clearListeners: clearListenerMiddleware,
|
| 561 |
+
} as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>
|
| 562 |
+
}
|