File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ import createNextState from 'immer' ;
2
+
3
+ const defaultReducer = ( state ) => state ;
4
+ const getType = ( slice , action ) =>
5
+ slice ? `${ slice } /${ action } ` : action ;
6
+
7
+ export default function createSlice ( {
8
+ slice = '' ,
9
+ actions = { } ,
10
+ initialState,
11
+ } ) {
12
+ const actionKeys = Object . keys ( actions ) ;
13
+
14
+ const reducerMap = actionKeys . reduce (
15
+ ( map , action ) => {
16
+ map [ getType ( slice , action ) ] = actions [ action ] ;
17
+ return map ;
18
+ } ,
19
+ { } ,
20
+ ) ;
21
+
22
+ const reducer = ( state = initialState , { type, payload } ) => {
23
+ const actionReducer = reducerMap [ type ] || defaultReducer ;
24
+ const produce = ( draft ) => actionReducer ( draft , payload ) ;
25
+ return createNextState ( state , produce ) ;
26
+ } ;
27
+
28
+ const actionMap = actionKeys . reduce (
29
+ ( map , action ) => {
30
+ map [ action ] = ( payload ) => ( {
31
+ type : getType ( slice , action ) ,
32
+ payload,
33
+ } ) ;
34
+
35
+ return map ;
36
+ } ,
37
+ { } ,
38
+ ) ;
39
+
40
+ return {
41
+ actions : actionMap ,
42
+ reducer,
43
+ slice,
44
+ } ;
45
+ }
Original file line number Diff line number Diff line change 1
1
export { configureStore , getDefaultMiddleware } from './configureStore'
2
2
export { createReducer } from './createReducer'
3
+ export { default as createSlice } from './createSlice' ;
3
4
4
5
export { default as createNextState } from 'immer'
5
6
export { combineReducers , compose } from 'redux'
You can’t perform that action at this time.
0 commit comments