Skip to content

Commit 865b171

Browse files
committed
initial work on create slice
1 parent 2f7f1e0 commit 865b171

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/createSlice.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

src/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
export { configureStore, getDefaultMiddleware } from './configureStore'
22
export { createReducer } from './createReducer'
3+
export { default as createSlice } from './createSlice';
34

45
export { default as createNextState } from 'immer'
56
export { combineReducers, compose } from 'redux'

0 commit comments

Comments
 (0)