-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
createSlice.ts
309 lines (280 loc) · 8.13 KB
/
createSlice.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { Reducer } from 'redux'
import {
ActionCreatorWithoutPayload,
createAction,
PayloadAction,
PayloadActionCreator,
PrepareAction,
_ActionCreatorWithPreparedPayload
} from './createAction'
import { CaseReducer, CaseReducers, createReducer } from './createReducer'
import {
ActionReducerMapBuilder,
executeReducerBuilderCallback
} from './mapBuilders'
import { NoInfer } from './tsHelpers'
/**
* An action creator attached to a slice.
*
* @deprecated please use PayloadActionCreator directly
*
* @public
*/
export type SliceActionCreator<P> = PayloadActionCreator<P>
/**
* The return value of `createSlice`
*
* @public
*/
export interface Slice<
State = any,
CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,
Name extends string = string
> {
/**
* The slice name.
*/
name: Name
/**
* The slice's reducer.
*/
reducer: Reducer<State>
/**
* Action creators for the types of actions that are handled by the slice
* reducer.
*/
actions: CaseReducerActions<CaseReducers>
/**
* The individual case reducer functions that were passed in the `reducers` parameter.
* This enables reuse and testing if they were defined inline when calling `createSlice`.
*/
caseReducers: SliceDefinedCaseReducers<CaseReducers>
}
/**
* Options for `createSlice()`.
*
* @public
*/
export interface CreateSliceOptions<
State = any,
CR extends SliceCaseReducers<State> = SliceCaseReducers<State>,
Name extends string = string
> {
/**
* The slice's name. Used to namespace the generated action types.
*/
name: Name
/**
* The initial state to be returned by the slice reducer.
*/
initialState: State
/**
* A mapping from action types to action-type-specific *case reducer*
* functions. For every action type, a matching action creator will be
* generated using `createAction()`.
*/
reducers: ValidateSliceCaseReducers<State, CR>
/**
* A callback that receives a *builder* object to define
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
*
* Alternatively, a mapping from action types to action-type-specific *case reducer*
* functions. These reducers should have existing action types used
* as the keys, and action creators will _not_ be generated.
*
* @example
```ts
import { createAction, createSlice, Action, AnyAction } from '@reduxjs/toolkit'
const incrementBy = createAction<number>('incrementBy')
const decrement = createAction('decrement')
interface RejectedAction extends Action {
error: Error
}
function isRejectedAction(action: AnyAction): action is RejectedAction {
return action.type.endsWith('rejected')
}
createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: builder => {
builder
.addCase(incrementBy, (state, action) => {
// action is inferred correctly here if using TS
})
// You can chain calls, or have separate `builder.addCase()` lines each time
.addCase(decrement, (state, action) => {})
// You can match a range of action types
.addMatcher(
isRejectedAction,
// `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
(state, action) => {}
)
// and provide a default case if no other handlers matched
.addDefaultCase((state, action) => {})
}
})
```
*/
extraReducers?:
| CaseReducers<NoInfer<State>, any>
| ((builder: ActionReducerMapBuilder<NoInfer<State>>) => void)
}
/**
* A CaseReducer with a `prepare` method.
*
* @public
*/
export type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
reducer: CaseReducer<State, Action>
prepare: PrepareAction<Action['payload']>
}
/**
* The type describing a slice's `reducers` option.
*
* @public
*/
export type SliceCaseReducers<State> = {
[K: string]:
| CaseReducer<State, PayloadAction<any>>
| CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>
}
/**
* Derives the slice's `actions` property from the `reducers` options
*
* @public
*/
export type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>> = {
[Type in keyof CaseReducers]: CaseReducers[Type] extends { prepare: any }
? ActionCreatorForCaseReducerWithPrepare<CaseReducers[Type]>
: ActionCreatorForCaseReducer<CaseReducers[Type]>
}
/**
* Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
*
* @internal
*/
type ActionCreatorForCaseReducerWithPrepare<
CR extends { prepare: any }
> = _ActionCreatorWithPreparedPayload<CR['prepare'], string>
/**
* Get a `PayloadActionCreator` type for a passed `CaseReducer`
*
* @internal
*/
type ActionCreatorForCaseReducer<CR> = CR extends (
state: any,
action: infer Action
) => any
? Action extends { payload: infer P }
? PayloadActionCreator<P>
: ActionCreatorWithoutPayload
: ActionCreatorWithoutPayload
/**
* Extracts the CaseReducers out of a `reducers` object, even if they are
* tested into a `CaseReducerWithPrepare`.
*
* @internal
*/
type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
[Type in keyof CaseReducers]: CaseReducers[Type] extends {
reducer: infer Reducer
}
? Reducer
: CaseReducers[Type]
}
/**
* Used on a SliceCaseReducers object.
* Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
* the `reducer` and the `prepare` function use the same type of `payload`.
*
* Might do additional such checks in the future.
*
* This type is only ever useful if you want to write your own wrapper around
* `createSlice`. Please don't use it otherwise!
*
* @public
*/
export type ValidateSliceCaseReducers<
S,
ACR extends SliceCaseReducers<S>
> = ACR &
{
[T in keyof ACR]: ACR[T] extends {
reducer(s: S, action?: infer A): any
}
? {
prepare(...a: never[]): Omit<A, 'type'>
}
: {}
}
function getType(slice: string, actionKey: string): string {
return `${slice}/${actionKey}`
}
/**
* A function that accepts an initial state, an object full of reducer
* functions, and a "slice name", and automatically generates
* action creators and action types that correspond to the
* reducers and state.
*
* The `reducer` argument is passed to `createReducer()`.
*
* @public
*/
export function createSlice<
State,
CaseReducers extends SliceCaseReducers<State>,
Name extends string = string
>(
options: CreateSliceOptions<State, CaseReducers, Name>
): Slice<State, CaseReducers, Name> {
const { name, initialState } = options
if (!name) {
throw new Error('`name` is a required option for createSlice')
}
const reducers = options.reducers || {}
const [
extraReducers = {},
actionMatchers = [],
defaultCaseReducer = undefined
] =
typeof options.extraReducers === 'undefined'
? []
: typeof options.extraReducers === 'function'
? executeReducerBuilderCallback(options.extraReducers)
: [options.extraReducers]
const reducerNames = Object.keys(reducers)
const sliceCaseReducersByName: Record<string, CaseReducer> = {}
const sliceCaseReducersByType: Record<string, CaseReducer> = {}
const actionCreators: Record<string, Function> = {}
reducerNames.forEach(reducerName => {
const maybeReducerWithPrepare = reducers[reducerName]
const type = getType(name, reducerName)
let caseReducer: CaseReducer<State, any>
let prepareCallback: PrepareAction<any> | undefined
if ('reducer' in maybeReducerWithPrepare) {
caseReducer = maybeReducerWithPrepare.reducer
prepareCallback = maybeReducerWithPrepare.prepare
} else {
caseReducer = maybeReducerWithPrepare
}
sliceCaseReducersByName[reducerName] = caseReducer
sliceCaseReducersByType[type] = caseReducer
actionCreators[reducerName] = prepareCallback
? createAction(type, prepareCallback)
: createAction(type)
})
const finalCaseReducers = { ...extraReducers, ...sliceCaseReducersByType }
const reducer = createReducer(
initialState,
finalCaseReducers as any,
actionMatchers,
defaultCaseReducer
)
return {
name,
reducer,
actions: actionCreators as any,
caseReducers: sliceCaseReducersByName as any
}
}