| 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 { ActionReducerMapBuilder, TypedActionCreator } from './mapBuilders' |
| 27 |
import { executeReducerBuilderCallback } from './mapBuilders' |
| 28 |
import type { Id, TypeGuard } from './tsHelpers' |
| 29 |
import { getOrInsertComputed } from './utils' |
| 30 |
|
| 31 |
const asyncThunkSymbol = /* @__PURE__ */ Symbol.for( |
| 32 |
'rtk-slice-createasyncthunk', |
| 33 |
) |
| 34 |
// type is annotated because it's too long to infer |
| 35 |
export const asyncThunkCreator: { |
| 36 |
[asyncThunkSymbol]: typeof _createAsyncThunk |
| 37 |
} = { |
| 38 |
[asyncThunkSymbol]: _createAsyncThunk, |
| 39 |
} |
| 40 |
|
| 41 |
type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & { |
| 42 |
reducerPath?: NewReducerPath |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* The return value of `createSlice` |
| 47 |
* |
| 48 |
* @public |
| 49 |
*/ |
| 50 |
export interface Slice< |
| 51 |
State = any, |
| 52 |
CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, |
| 53 |
Name extends string = string, |
| 54 |
ReducerPath extends string = Name, |
| 55 |
Selectors extends SliceSelectors<State> = SliceSelectors<State>, |
| 56 |
> { |
| 57 |
/** |
| 58 |
* The slice name. |
| 59 |
*/ |
| 60 |
name: Name |
| 61 |
|
| 62 |
/** |
| 63 |
* The slice reducer path. |
| 64 |
*/ |
| 65 |
reducerPath: ReducerPath |
| 66 |
|
| 67 |
/** |
| 68 |
* The slice's reducer. |
| 69 |
*/ |
| 70 |
reducer: Reducer<State> |
| 71 |
|
| 72 |
/** |
| 73 |
* Action creators for the types of actions that are handled by the slice |
| 74 |
* reducer. |
| 75 |
*/ |
| 76 |
actions: CaseReducerActions<CaseReducers, Name> |
| 77 |
|
| 78 |
/** |
| 79 |
* The individual case reducer functions that were passed in the `reducers` parameter. |
| 80 |
* This enables reuse and testing if they were defined inline when calling `createSlice`. |
| 81 |
*/ |
| 82 |
caseReducers: SliceDefinedCaseReducers<CaseReducers> |
| 83 |
|
| 84 |
/** |
| 85 |
* Provides access to the initial state value given to the slice. |
| 86 |
* If a lazy state initializer was provided, it will be called and a fresh value returned. |
| 87 |
*/ |
| 88 |
getInitialState: () => State |
| 89 |
|
| 90 |
/** |
| 91 |
* Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter) |
| 92 |
*/ |
| 93 |
getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>> |
| 94 |
|
| 95 |
/** |
| 96 |
* Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state) |
| 97 |
*/ |
| 98 |
getSelectors<RootState>( |
| 99 |
selectState: (rootState: RootState) => State, |
| 100 |
): Id<SliceDefinedSelectors<State, Selectors, RootState>> |
| 101 |
|
| 102 |
/** |
| 103 |
* Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case) |
| 104 |
* |
| 105 |
* Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`. |
| 106 |
*/ |
| 107 |
get selectors(): Id< |
| 108 |
SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }> |
| 109 |
> |
| 110 |
|
| 111 |
/** |
| 112 |
* Inject slice into provided reducer (return value from `combineSlices`), and return injected slice. |
| 113 |
*/ |
| 114 |
injectInto<NewReducerPath extends string = ReducerPath>( |
| 115 |
this: this, |
| 116 |
injectable: { |
| 117 |
inject: ( |
| 118 |
slice: { reducerPath: string; reducer: Reducer }, |
| 119 |
config?: InjectConfig, |
| 120 |
) => void |
| 121 |
}, |
| 122 |
config?: InjectIntoConfig<NewReducerPath>, |
| 123 |
): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors> |
| 124 |
|
| 125 |
/** |
| 126 |
* Select the slice state, using the slice's current reducerPath. |
| 127 |
* |
| 128 |
* Will throw an error if slice is not found. |
| 129 |
*/ |
| 130 |
selectSlice(state: { [K in ReducerPath]: State }): State |
| 131 |
} |
| 132 |
|
| 133 |
/** |
| 134 |
* A slice after being called with `injectInto(reducer)`. |
| 135 |
* |
| 136 |
* Selectors can now be called with an `undefined` value, in which case they use the slice's initial state. |
| 137 |
*/ |
| 138 |
type InjectedSlice< |
| 139 |
State = any, |
| 140 |
CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, |
| 141 |
Name extends string = string, |
| 142 |
ReducerPath extends string = Name, |
| 143 |
Selectors extends SliceSelectors<State> = SliceSelectors<State>, |
| 144 |
> = Omit< |
| 145 |
Slice<State, CaseReducers, Name, ReducerPath, Selectors>, |
| 146 |
'getSelectors' | 'selectors' |
| 147 |
> & { |
| 148 |
/** |
| 149 |
* Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter) |
| 150 |
*/ |
| 151 |
getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>> |
| 152 |
|
| 153 |
/** |
| 154 |
* Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state) |
| 155 |
*/ |
| 156 |
getSelectors<RootState>( |
| 157 |
selectState: (rootState: RootState) => State | undefined, |
| 158 |
): Id<SliceDefinedSelectors<State, Selectors, RootState>> |
| 159 |
|
| 160 |
/** |
| 161 |
* Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case) |
| 162 |
* |
| 163 |
* Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`. |
| 164 |
*/ |
| 165 |
get selectors(): Id< |
| 166 |
SliceDefinedSelectors< |
| 167 |
State, |
| 168 |
Selectors, |
| 169 |
{ [K in ReducerPath]?: State | undefined } |
| 170 |
> |
| 171 |
> |
| 172 |
|
| 173 |
/** |
| 174 |
* Select the slice state, using the slice's current reducerPath. |
| 175 |
* |
| 176 |
* Returns initial state if slice is not found. |
| 177 |
*/ |
| 178 |
selectSlice(state: { [K in ReducerPath]?: State | undefined }): State |
| 179 |
} |
| 180 |
|
| 181 |
/** |
| 182 |
* Options for `createSlice()`. |
| 183 |
* |
| 184 |
* @public |
| 185 |
*/ |
| 186 |
export interface CreateSliceOptions< |
| 187 |
State = any, |
| 188 |
CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, |
| 189 |
Name extends string = string, |
| 190 |
ReducerPath extends string = Name, |
| 191 |
Selectors extends SliceSelectors<State> = SliceSelectors<State>, |
| 192 |
> { |
| 193 |
/** |
| 194 |
* The slice's name. Used to namespace the generated action types. |
| 195 |
*/ |
| 196 |
name: Name |
| 197 |
|
| 198 |
/** |
| 199 |
* The slice's reducer path. Used when injecting into a combined slice reducer. |
| 200 |
*/ |
| 201 |
reducerPath?: ReducerPath |
| 202 |
|
| 203 |
/** |
| 204 |
* 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`. |
| 205 |
*/ |
| 206 |
initialState: State | (() => State) |
| 207 |
|
| 208 |
/** |
| 209 |
* A mapping from action types to action-type-specific *case reducer* |
| 210 |
* functions. For every action type, a matching action creator will be |
| 211 |
* generated using `createAction()`. |
| 212 |
*/ |
| 213 |
reducers: |
| 214 |
| ValidateSliceCaseReducers<State, CR> |
| 215 |
| ((creators: ReducerCreators<State>) => CR) |
| 216 |
|
| 217 |
/** |
| 218 |
* A callback that receives a *builder* object to define |
| 219 |
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`. |
| 220 |
* |
| 221 |
* |
| 222 |
* @example |
| 223 |
```ts |
| 224 |
import { createAction, createSlice, Action } from '@reduxjs/toolkit' |
| 225 |
const incrementBy = createAction<number>('incrementBy') |
| 226 |
const decrement = createAction('decrement') |
| 227 |
|
| 228 |
interface RejectedAction extends Action { |
| 229 |
error: Error |
| 230 |
} |
| 231 |
|
| 232 |
function isRejectedAction(action: Action): action is RejectedAction { |
| 233 |
return action.type.endsWith('rejected') |
| 234 |
} |
| 235 |
|
| 236 |
createSlice({ |
| 237 |
name: 'counter', |
| 238 |
initialState: 0, |
| 239 |
reducers: {}, |
| 240 |
extraReducers: builder => { |
| 241 |
builder |
| 242 |
.addCase(incrementBy, (state, action) => { |
| 243 |
// action is inferred correctly here if using TS |
| 244 |
}) |
| 245 |
// You can chain calls, or have separate `builder.addCase()` lines each time |
| 246 |
.addCase(decrement, (state, action) => {}) |
| 247 |
// You can match a range of action types |
| 248 |
.addMatcher( |
| 249 |
isRejectedAction, |
| 250 |
// `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard |
| 251 |
(state, action) => {} |
| 252 |
) |
| 253 |
// and provide a default case if no other handlers matched |
| 254 |
.addDefaultCase((state, action) => {}) |
| 255 |
} |
| 256 |
}) |
| 257 |
``` |
| 258 |
*/ |
| 259 |
extraReducers?: (builder: ActionReducerMapBuilder<State>) => void |
| 260 |
|
| 261 |
/** |
| 262 |
* A map of selectors that receive the slice's state and any additional arguments, and return a result. |
| 263 |
*/ |
| 264 |
selectors?: Selectors |
| 265 |
} |
| 266 |
|
| 267 |
export enum ReducerType { |
| 268 |
reducer = 'reducer', |
| 269 |
reducerWithPrepare = 'reducerWithPrepare', |
| 270 |
asyncThunk = 'asyncThunk', |
| 271 |
} |
| 272 |
|
| 273 |
type ReducerDefinition<T extends ReducerType = ReducerType> = { |
| 274 |
_reducerDefinitionType: T |
| 275 |
} |
| 276 |
|
| 277 |
export type CaseReducerDefinition< |
| 278 |
S = any, |
| 279 |
A extends Action = UnknownAction, |
| 280 |
> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer> |
| 281 |
|
| 282 |
/** |
| 283 |
* A CaseReducer with a `prepare` method. |
| 284 |
* |
| 285 |
* @public |
| 286 |
*/ |
| 287 |
export type CaseReducerWithPrepare<State, Action extends PayloadAction> = { |
| 288 |
reducer: CaseReducer<State, Action> |
| 289 |
prepare: PrepareAction<Action['payload']> |
| 290 |
} |
| 291 |
|
| 292 |
export interface CaseReducerWithPrepareDefinition< |
| 293 |
State, |
| 294 |
Action extends PayloadAction, |
| 295 |
> extends CaseReducerWithPrepare<State, Action>, |
| 296 |
ReducerDefinition<ReducerType.reducerWithPrepare> {} |
| 297 |
|
| 298 |
type AsyncThunkSliceReducerConfig< |
| 299 |
State, |
| 300 |
ThunkArg extends any, |
| 301 |
Returned = unknown, |
| 302 |
ThunkApiConfig extends AsyncThunkConfig = {}, |
| 303 |
> = { |
| 304 |
pending?: CaseReducer< |
| 305 |
State, |
| 306 |
ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']> |
| 307 |
> |
| 308 |
rejected?: CaseReducer< |
| 309 |
State, |
| 310 |
ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']> |
| 311 |
> |
| 312 |
fulfilled?: CaseReducer< |
| 313 |
State, |
| 314 |
ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']> |
| 315 |
> |
| 316 |
settled?: CaseReducer< |
| 317 |
State, |
| 318 |
ReturnType< |
| 319 |
AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled'] |
| 320 |
> |
| 321 |
> |
| 322 |
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig> |
| 323 |
} |
| 324 |
|
| 325 |
type AsyncThunkSliceReducerDefinition< |
| 326 |
State, |
| 327 |
ThunkArg extends any, |
| 328 |
Returned = unknown, |
| 329 |
ThunkApiConfig extends AsyncThunkConfig = {}, |
| 330 |
> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & |
| 331 |
ReducerDefinition<ReducerType.asyncThunk> & { |
| 332 |
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig> |
| 333 |
} |
| 334 |
|
| 335 |
/** |
| 336 |
* Providing these as part of the config would cause circular types, so we disallow passing them |
| 337 |
*/ |
| 338 |
type PreventCircular<ThunkApiConfig> = { |
| 339 |
[K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' |
| 340 |
? never |
| 341 |
: ThunkApiConfig[K] |
| 342 |
} |
| 343 |
|
| 344 |
interface AsyncThunkCreator< |
| 345 |
State, |
| 346 |
CurriedThunkApiConfig extends |
| 347 |
PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>, |
| 348 |
> { |
| 349 |
<Returned, ThunkArg = void>( |
| 350 |
payloadCreator: AsyncThunkPayloadCreator< |
| 351 |
Returned, |
| 352 |
ThunkArg, |
| 353 |
CurriedThunkApiConfig |
| 354 |
>, |
| 355 |
config?: AsyncThunkSliceReducerConfig< |
| 356 |
State, |
| 357 |
ThunkArg, |
| 358 |
Returned, |
| 359 |
CurriedThunkApiConfig |
| 360 |
>, |
| 361 |
): AsyncThunkSliceReducerDefinition< |
| 362 |
State, |
| 363 |
ThunkArg, |
| 364 |
Returned, |
| 365 |
CurriedThunkApiConfig |
| 366 |
> |
| 367 |
< |
| 368 |
Returned, |
| 369 |
ThunkArg, |
| 370 |
ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}, |
| 371 |
>( |
| 372 |
payloadCreator: AsyncThunkPayloadCreator< |
| 373 |
Returned, |
| 374 |
ThunkArg, |
| 375 |
ThunkApiConfig |
| 376 |
>, |
| 377 |
config?: AsyncThunkSliceReducerConfig< |
| 378 |
State, |
| 379 |
ThunkArg, |
| 380 |
Returned, |
| 381 |
ThunkApiConfig |
| 382 |
>, |
| 383 |
): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig> |
| 384 |
withTypes< |
| 385 |
ThunkApiConfig extends PreventCircular<AsyncThunkConfig>, |
| 386 |
>(): AsyncThunkCreator< |
| 387 |
State, |
| 388 |
OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig> |
| 389 |
> |
| 390 |
} |
| 391 |
|
| 392 |
export interface ReducerCreators<State> { |
| 393 |
reducer( |
| 394 |
caseReducer: CaseReducer<State, PayloadAction>, |
| 395 |
): CaseReducerDefinition<State, PayloadAction> |
| 396 |
reducer<Payload>( |
| 397 |
caseReducer: CaseReducer<State, PayloadAction<Payload>>, |
| 398 |
): CaseReducerDefinition<State, PayloadAction<Payload>> |
| 399 |
|
| 400 |
asyncThunk: AsyncThunkCreator<State> |
| 401 |
|
| 402 |
preparedReducer<Prepare extends PrepareAction<any>>( |
| 403 |
prepare: Prepare, |
| 404 |
reducer: CaseReducer< |
| 405 |
State, |
| 406 |
ReturnType<_ActionCreatorWithPreparedPayload<Prepare>> |
| 407 |
>, |
| 408 |
): { |
| 409 |
_reducerDefinitionType: ReducerType.reducerWithPrepare |
| 410 |
prepare: Prepare |
| 411 |
reducer: CaseReducer< |
| 412 |
State, |
| 413 |
ReturnType<_ActionCreatorWithPreparedPayload<Prepare>> |
| 414 |
> |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
/** |
| 419 |
* The type describing a slice's `reducers` option. |
| 420 |
* |
| 421 |
* @public |
| 422 |
*/ |
| 423 |
export type SliceCaseReducers<State> = |
| 424 |
| Record<string, ReducerDefinition> |
| 425 |
| Record< |
| 426 |
string, |
| 427 |
| CaseReducer<State, PayloadAction<any>> |
| 428 |
| CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>> |
| 429 |
> |
| 430 |
|
| 431 |
/** |
| 432 |
* The type describing a slice's `selectors` option. |
| 433 |
*/ |
| 434 |
export type SliceSelectors<State> = { |
| 435 |
[K: string]: (sliceState: State, ...args: any[]) => any |
| 436 |
} |
| 437 |
|
| 438 |
type SliceActionType< |
| 439 |
SliceName extends string, |
| 440 |
ActionName extends keyof any, |
| 441 |
> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string |
| 442 |
|
| 443 |
/** |
| 444 |
* Derives the slice's `actions` property from the `reducers` options |
| 445 |
* |
| 446 |
* @public |
| 447 |
*/ |
| 448 |
export type CaseReducerActions< |
| 449 |
CaseReducers extends SliceCaseReducers<any>, |
| 450 |
SliceName extends string, |
| 451 |
> = { |
| 452 |
[Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition |
| 453 |
? Definition extends { prepare: any } |
| 454 |
? ActionCreatorForCaseReducerWithPrepare< |
| 455 |
Definition, |
| 456 |
SliceActionType<SliceName, Type> |
| 457 |
> |
| 458 |
: Definition extends AsyncThunkSliceReducerDefinition< |
| 459 |
any, |
| 460 |
infer ThunkArg, |
| 461 |
infer Returned, |
| 462 |
infer ThunkApiConfig |
| 463 |
> |
| 464 |
? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> |
| 465 |
: Definition extends { reducer: any } |
| 466 |
? ActionCreatorForCaseReducer< |
| 467 |
Definition['reducer'], |
| 468 |
SliceActionType<SliceName, Type> |
| 469 |
> |
| 470 |
: ActionCreatorForCaseReducer< |
| 471 |
Definition, |
| 472 |
SliceActionType<SliceName, Type> |
| 473 |
> |
| 474 |
: never |
| 475 |
} |
| 476 |
|
| 477 |
/** |
| 478 |
* Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare` |
| 479 |
* |
| 480 |
* @internal |
| 481 |
*/ |
| 482 |
type ActionCreatorForCaseReducerWithPrepare< |
| 483 |
CR extends { prepare: any }, |
| 484 |
Type extends string, |
| 485 |
> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type> |
| 486 |
|
| 487 |
/** |
| 488 |
* Get a `PayloadActionCreator` type for a passed `CaseReducer` |
| 489 |
* |
| 490 |
* @internal |
| 491 |
*/ |
| 492 |
type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends ( |
| 493 |
state: any, |
| 494 |
action: infer Action, |
| 495 |
) => any |
| 496 |
? Action extends { payload: infer P } |
| 497 |
? PayloadActionCreator<P, Type> |
| 498 |
: ActionCreatorWithoutPayload<Type> |
| 499 |
: ActionCreatorWithoutPayload<Type> |
| 500 |
|
| 501 |
/** |
| 502 |
* Extracts the CaseReducers out of a `reducers` object, even if they are |
| 503 |
* tested into a `CaseReducerWithPrepare`. |
| 504 |
* |
| 505 |
* @internal |
| 506 |
*/ |
| 507 |
type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = { |
| 508 |
[Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition |
| 509 |
? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> |
| 510 |
? Id< |
| 511 |
Pick< |
| 512 |
Required<Definition>, |
| 513 |
'fulfilled' | 'rejected' | 'pending' | 'settled' |
| 514 |
> |
| 515 |
> |
| 516 |
: Definition extends { |
| 517 |
reducer: infer Reducer |
| 518 |
} |
| 519 |
? Reducer |
| 520 |
: Definition |
| 521 |
: never |
| 522 |
} |
| 523 |
|
| 524 |
type RemappedSelector<S extends Selector, NewState> = |
| 525 |
S extends Selector<any, infer R, infer P> |
| 526 |
? Selector<NewState, R, P> & { unwrapped: S } |
| 527 |
: never |
| 528 |
|
| 529 |
/** |
| 530 |
* Extracts the final selector type from the `selectors` object. |
| 531 |
* |
| 532 |
* Removes the `string` index signature from the default value. |
| 533 |
*/ |
| 534 |
type SliceDefinedSelectors< |
| 535 |
State, |
| 536 |
Selectors extends SliceSelectors<State>, |
| 537 |
RootState, |
| 538 |
> = { |
| 539 |
[K in keyof Selectors as string extends K ? never : K]: RemappedSelector< |
| 540 |
Selectors[K], |
| 541 |
RootState |
| 542 |
> |
| 543 |
} |
| 544 |
|
| 545 |
/** |
| 546 |
* Used on a SliceCaseReducers object. |
| 547 |
* Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that |
| 548 |
* the `reducer` and the `prepare` function use the same type of `payload`. |
| 549 |
* |
| 550 |
* Might do additional such checks in the future. |
| 551 |
* |
| 552 |
* This type is only ever useful if you want to write your own wrapper around |
| 553 |
* `createSlice`. Please don't use it otherwise! |
| 554 |
* |
| 555 |
* @public |
| 556 |
*/ |
| 557 |
export type ValidateSliceCaseReducers< |
| 558 |
S, |
| 559 |
ACR extends SliceCaseReducers<S>, |
| 560 |
> = ACR & { |
| 561 |
[T in keyof ACR]: ACR[T] extends { |
| 562 |
reducer(s: S, action?: infer A): any |
| 563 |
} |
| 564 |
? { |
| 565 |
prepare(...a: never[]): Omit<A, 'type'> |
| 566 |
} |
| 567 |
: {} |
| 568 |
} |
| 569 |
|
| 570 |
function getType(slice: string, actionKey: string): string { |
| 571 |
return `${slice}/${actionKey}` |
| 572 |
} |
| 573 |
|
| 574 |
interface BuildCreateSliceConfig { |
| 575 |
creators?: { |
| 576 |
asyncThunk?: typeof asyncThunkCreator |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) { |
| 581 |
const cAT = creators?.asyncThunk?.[asyncThunkSymbol] |
| 582 |
return function createSlice< |
| 583 |
State, |
| 584 |
CaseReducers extends SliceCaseReducers<State>, |
| 585 |
Name extends string, |
| 586 |
Selectors extends SliceSelectors<State>, |
| 587 |
ReducerPath extends string = Name, |
| 588 |
>( |
| 589 |
options: CreateSliceOptions< |
| 590 |
State, |
| 591 |
CaseReducers, |
| 592 |
Name, |
| 593 |
ReducerPath, |
| 594 |
Selectors |
| 595 |
>, |
| 596 |
): Slice<State, CaseReducers, Name, ReducerPath, Selectors> { |
| 597 |
const { name, reducerPath = name as unknown as ReducerPath } = options |
| 598 |
if (!name) { |
| 599 |
throw new Error('`name` is a required option for createSlice') |
| 600 |
} |
| 601 |
|
| 602 |
if ( |
| 603 |
typeof process !== 'undefined' && |
| 604 |
process.env.NODE_ENV === 'development' |
| 605 |
) { |
| 606 |
if (options.initialState === undefined) { |
| 607 |
console.error( |
| 608 |
'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`', |
| 609 |
) |
| 610 |
} |
| 611 |
} |
| 612 |
|
| 613 |
const reducers = |
| 614 |
(typeof options.reducers === 'function' |
| 615 |
? options.reducers(buildReducerCreators<State>()) |
| 616 |
: options.reducers) || {} |
| 617 |
|
| 618 |
const reducerNames = Object.keys(reducers) |
| 619 |
|
| 620 |
const context: ReducerHandlingContext<State> = { |
| 621 |
sliceCaseReducersByName: {}, |
| 622 |
sliceCaseReducersByType: {}, |
| 623 |
actionCreators: {}, |
| 624 |
sliceMatchers: [], |
| 625 |
} |
| 626 |
|
| 627 |
const contextMethods: ReducerHandlingContextMethods<State> = { |
| 628 |
addCase( |
| 629 |
typeOrActionCreator: string | TypedActionCreator<any>, |
| 630 |
reducer: CaseReducer<State>, |
| 631 |
) { |
| 632 |
const type = |
| 633 |
typeof typeOrActionCreator === 'string' |
| 634 |
? typeOrActionCreator |
| 635 |
: typeOrActionCreator.type |
| 636 |
if (!type) { |
| 637 |
throw new Error( |
| 638 |
'`context.addCase` cannot be called with an empty action type', |
| 639 |
) |
| 640 |
} |
| 641 |
if (type in context.sliceCaseReducersByType) { |
| 642 |
throw new Error( |
| 643 |
'`context.addCase` cannot be called with two reducers for the same action type: ' + |
| 644 |
type, |
| 645 |
) |
| 646 |
} |
| 647 |
context.sliceCaseReducersByType[type] = reducer |
| 648 |
return contextMethods |
| 649 |
}, |
| 650 |
addMatcher(matcher, reducer) { |
| 651 |
context.sliceMatchers.push({ matcher, reducer }) |
| 652 |
return contextMethods |
| 653 |
}, |
| 654 |
exposeAction(name, actionCreator) { |
| 655 |
context.actionCreators[name] = actionCreator |
| 656 |
return contextMethods |
| 657 |
}, |
| 658 |
exposeCaseReducer(name, reducer) { |
| 659 |
context.sliceCaseReducersByName[name] = reducer |
| 660 |
return contextMethods |
| 661 |
}, |
| 662 |
} |
| 663 |
|
| 664 |
reducerNames.forEach((reducerName) => { |
| 665 |
const reducerDefinition = reducers[reducerName] |
| 666 |
const reducerDetails: ReducerDetails = { |
| 667 |
reducerName, |
| 668 |
type: getType(name, reducerName), |
| 669 |
createNotation: typeof options.reducers === 'function', |
| 670 |
} |
| 671 |
if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) { |
| 672 |
handleThunkCaseReducerDefinition( |
| 673 |
reducerDetails, |
| 674 |
reducerDefinition, |
| 675 |
contextMethods, |
| 676 |
cAT, |
| 677 |
) |
| 678 |
} else { |
| 679 |
handleNormalReducerDefinition<State>( |
| 680 |
reducerDetails, |
| 681 |
reducerDefinition as any, |
| 682 |
contextMethods, |
| 683 |
) |
| 684 |
} |
| 685 |
}) |
| 686 |
|
| 687 |
function buildReducer() { |
| 688 |
if (process.env.NODE_ENV !== 'production') { |
| 689 |
if (typeof options.extraReducers === 'object') { |
| 690 |
throw new Error( |
| 691 |
"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice", |
| 692 |
) |
| 693 |
} |
| 694 |
} |
| 695 |
const [ |
| 696 |
extraReducers = {}, |
| 697 |
actionMatchers = [], |
| 698 |
defaultCaseReducer = undefined, |
| 699 |
] = |
| 700 |
typeof options.extraReducers === 'function' |
| 701 |
? executeReducerBuilderCallback(options.extraReducers) |
| 702 |
: [options.extraReducers] |
| 703 |
|
| 704 |
const finalCaseReducers = { |
| 705 |
...extraReducers, |
| 706 |
...context.sliceCaseReducersByType, |
| 707 |
} |
| 708 |
|
| 709 |
return createReducer(options.initialState, (builder) => { |
| 710 |
for (let key in finalCaseReducers) { |
| 711 |
builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>) |
| 712 |
} |
| 713 |
for (let sM of context.sliceMatchers) { |
| 714 |
builder.addMatcher(sM.matcher, sM.reducer) |
| 715 |
} |
| 716 |
for (let m of actionMatchers) { |
| 717 |
builder.addMatcher(m.matcher, m.reducer) |
| 718 |
} |
| 719 |
if (defaultCaseReducer) { |
| 720 |
builder.addDefaultCase(defaultCaseReducer) |
| 721 |
} |
| 722 |
}) |
| 723 |
} |
| 724 |
|
| 725 |
const selectSelf = (state: State) => state |
| 726 |
|
| 727 |
const injectedSelectorCache = new Map< |
| 728 |
boolean, |
| 729 |
WeakMap< |
| 730 |
(rootState: any) => State | undefined, |
| 731 |
Record<string, (rootState: any) => any> |
| 732 |
> |
| 733 |
>() |
| 734 |
|
| 735 |
let _reducer: ReducerWithInitialState<State> |
| 736 |
|
| 737 |
function reducer(state: State | undefined, action: UnknownAction) { |
| 738 |
if (!_reducer) _reducer = buildReducer() |
| 739 |
|
| 740 |
return _reducer(state, action) |
| 741 |
} |
| 742 |
|
| 743 |
function getInitialState() { |
| 744 |
if (!_reducer) _reducer = buildReducer() |
| 745 |
|
| 746 |
return _reducer.getInitialState() |
| 747 |
} |
| 748 |
|
| 749 |
function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>( |
| 750 |
reducerPath: CurrentReducerPath, |
| 751 |
injected = false, |
| 752 |
): Pick< |
| 753 |
Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>, |
| 754 |
'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath' |
| 755 |
> { |
| 756 |
function selectSlice(state: { [K in CurrentReducerPath]: State }) { |
| 757 |
let sliceState = state[reducerPath] |
| 758 |
if (typeof sliceState === 'undefined') { |
| 759 |
if (injected) { |
| 760 |
sliceState = getInitialState() |
| 761 |
} else if (process.env.NODE_ENV !== 'production') { |
| 762 |
throw new Error( |
| 763 |
'selectSlice returned undefined for an uninjected slice reducer', |
| 764 |
) |
| 765 |
} |
| 766 |
} |
| 767 |
return sliceState |
| 768 |
} |
| 769 |
function getSelectors( |
| 770 |
selectState: (rootState: any) => State = selectSelf, |
| 771 |
) { |
| 772 |
const selectorCache = getOrInsertComputed( |
| 773 |
injectedSelectorCache, |
| 774 |
injected, |
| 775 |
() => new WeakMap(), |
| 776 |
) |
| 777 |
|
| 778 |
return getOrInsertComputed(selectorCache, selectState, () => { |
| 779 |
const map: Record<string, Selector<any, any>> = {} |
| 780 |
for (const [name, selector] of Object.entries( |
| 781 |
options.selectors ?? {}, |
| 782 |
)) { |
| 783 |
map[name] = wrapSelector( |
| 784 |
selector, |
| 785 |
selectState, |
| 786 |
getInitialState, |
| 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 |
* context.exposeAction("addPost", createAction<Post>("addPost")); |
| 911 |
* |
| 912 |
* export const { addPost } = slice.actions |
| 913 |
* |
| 914 |
* dispatch(addPost(post)) |
| 915 |
*/ |
| 916 |
exposeAction( |
| 917 |
name: string, |
| 918 |
actionCreator: Function, |
| 919 |
): ReducerHandlingContextMethods<State> |
| 920 |
/** |
| 921 |
* Add a case reducer to be exposed under the final `slice.caseReducers` key. |
| 922 |
* @param name The key to be exposed as. |
| 923 |
* @param reducer The reducer to expose. |
| 924 |
* @example |
| 925 |
* context.exposeCaseReducer("addPost", (state, action: PayloadAction<Post>) => { |
| 926 |
* state.push(action.payload) |
| 927 |
* }) |
| 928 |
* |
| 929 |
* slice.caseReducers.addPost([], addPost(post)) |
| 930 |
*/ |
| 931 |
exposeCaseReducer( |
| 932 |
name: string, |
| 933 |
reducer: |
| 934 |
| CaseReducer<State, any> |
| 935 |
| Pick< |
| 936 |
AsyncThunkSliceReducerDefinition<State, any, any, any>, |
| 937 |
'fulfilled' | 'rejected' | 'pending' | 'settled' |
| 938 |
>, |
| 939 |
): ReducerHandlingContextMethods<State> |
| 940 |
} |
| 941 |
|
| 942 |
interface ReducerDetails { |
| 943 |
/** The key the reducer was defined under */ |
| 944 |
reducerName: string |
| 945 |
/** The predefined action type, i.e. `${slice.name}/${reducerName}` */ |
| 946 |
type: string |
| 947 |
/** Whether create. notation was used when defining reducers */ |
| 948 |
createNotation: boolean |
| 949 |
} |
| 950 |
|
| 951 |
function buildReducerCreators<State>(): ReducerCreators<State> { |
| 952 |
function asyncThunk( |
| 953 |
payloadCreator: AsyncThunkPayloadCreator<any, any>, |
| 954 |
config: AsyncThunkSliceReducerConfig<State, any>, |
| 955 |
): AsyncThunkSliceReducerDefinition<State, any> { |
| 956 |
return { |
| 957 |
_reducerDefinitionType: ReducerType.asyncThunk, |
| 958 |
payloadCreator, |
| 959 |
...config, |
| 960 |
} |
| 961 |
} |
| 962 |
asyncThunk.withTypes = () => asyncThunk |
| 963 |
return { |
| 964 |
reducer(caseReducer: CaseReducer<State, any>) { |
| 965 |
return Object.assign( |
| 966 |
{ |
| 967 |
// hack so the wrapping function has the same name as the original |
| 968 |
// we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original |
| 969 |
[caseReducer.name](...args: Parameters<typeof caseReducer>) { |
| 970 |
return caseReducer(...args) |
| 971 |
}, |
| 972 |
}[caseReducer.name], |
| 973 |
{ |
| 974 |
_reducerDefinitionType: ReducerType.reducer, |
| 975 |
} as const, |
| 976 |
) |
| 977 |
}, |
| 978 |
preparedReducer(prepare, reducer) { |
| 979 |
return { |
| 980 |
_reducerDefinitionType: ReducerType.reducerWithPrepare, |
| 981 |
prepare, |
| 982 |
reducer, |
| 983 |
} |
| 984 |
}, |
| 985 |
asyncThunk: asyncThunk as any, |
| 986 |
} |
| 987 |
} |
| 988 |
|
| 989 |
function handleNormalReducerDefinition<State>( |
| 990 |
{ type, reducerName, createNotation }: ReducerDetails, |
| 991 |
maybeReducerWithPrepare: |
| 992 |
| CaseReducer<State, { payload: any; type: string }> |
| 993 |
| CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>, |
| 994 |
context: ReducerHandlingContextMethods<State>, |
| 995 |
) { |
| 996 |
let caseReducer: CaseReducer<State, any> |
| 997 |
let prepareCallback: PrepareAction<any> | undefined |
| 998 |
if ('reducer' in maybeReducerWithPrepare) { |
| 999 |
if ( |
| 1000 |
createNotation && |
| 1001 |
!isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare) |
| 1002 |
) { |
| 1003 |
throw new Error( |
| 1004 |
'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.', |
| 1005 |
) |
| 1006 |
} |
| 1007 |
caseReducer = maybeReducerWithPrepare.reducer |
| 1008 |
prepareCallback = maybeReducerWithPrepare.prepare |
| 1009 |
} else { |
| 1010 |
caseReducer = maybeReducerWithPrepare |
| 1011 |
} |
| 1012 |
context |
| 1013 |
.addCase(type, caseReducer) |
| 1014 |
.exposeCaseReducer(reducerName, caseReducer) |
| 1015 |
.exposeAction( |
| 1016 |
reducerName, |
| 1017 |
prepareCallback |
| 1018 |
? createAction(type, prepareCallback) |
| 1019 |
: createAction(type), |
| 1020 |
) |
| 1021 |
} |
| 1022 |
|
| 1023 |
function isAsyncThunkSliceReducerDefinition<State>( |
| 1024 |
reducerDefinition: any, |
| 1025 |
): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> { |
| 1026 |
return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk |
| 1027 |
} |
| 1028 |
|
| 1029 |
function isCaseReducerWithPrepareDefinition<State>( |
| 1030 |
reducerDefinition: any, |
| 1031 |
): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> { |
| 1032 |
return ( |
| 1033 |
reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare |
| 1034 |
) |
| 1035 |
} |
| 1036 |
|
| 1037 |
function handleThunkCaseReducerDefinition<State>( |
| 1038 |
{ type, reducerName }: ReducerDetails, |
| 1039 |
reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>, |
| 1040 |
context: ReducerHandlingContextMethods<State>, |
| 1041 |
cAT: typeof _createAsyncThunk | undefined, |
| 1042 |
) { |
| 1043 |
if (!cAT) { |
| 1044 |
throw new Error( |
| 1045 |
'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' + |
| 1046 |
'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.', |
| 1047 |
) |
| 1048 |
} |
| 1049 |
const { payloadCreator, fulfilled, pending, rejected, settled, options } = |
| 1050 |
reducerDefinition |
| 1051 |
const thunk = cAT(type, payloadCreator, options as any) |
| 1052 |
context.exposeAction(reducerName, thunk) |
| 1053 |
|
| 1054 |
if (fulfilled) { |
| 1055 |
context.addCase(thunk.fulfilled, fulfilled) |
| 1056 |
} |
| 1057 |
if (pending) { |
| 1058 |
context.addCase(thunk.pending, pending) |
| 1059 |
} |
| 1060 |
if (rejected) { |
| 1061 |
context.addCase(thunk.rejected, rejected) |
| 1062 |
} |
| 1063 |
if (settled) { |
| 1064 |
context.addMatcher(thunk.settled, settled) |
| 1065 |
} |
| 1066 |
|
| 1067 |
context.exposeCaseReducer(reducerName, { |
| 1068 |
fulfilled: fulfilled || noop, |
| 1069 |
pending: pending || noop, |
| 1070 |
rejected: rejected || noop, |
| 1071 |
settled: settled || noop, |
| 1072 |
}) |
| 1073 |
} |
| 1074 |
|
| 1075 |
function noop() {} |