Skip to content

Commit 6502fd4

Browse files
committed
Added reducer generator
1 parent bdec1e5 commit 6502fd4

File tree

5 files changed

+48
-14
lines changed

5 files changed

+48
-14
lines changed

README.md

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,11 +1106,10 @@ export default combineReducers<TodosState, TodosAction>({
11061106
return [...state, action.payload];
11071107

11081108
case TOGGLE:
1109-
return state.map(
1110-
item =>
1111-
item.id === action.payload
1112-
? { ...item, completed: !item.completed }
1113-
: item
1109+
return state.map(item =>
1110+
item.id === action.payload
1111+
? { ...item, completed: !item.completed }
1112+
: item
11141113
);
11151114

11161115
default:

playground/package-lock.json

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

playground/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
"ts-jest": "22.4.6",
5757
"tslint": "5.12.1",
5858
"tslint-react": "3.6.0",
59-
"typescript": "3.1.6",
59+
"typescript": "3.0.3",
6060
"webpack": "3.11.0",
6161
"webpack-blocks": "1.0.0"
6262
}

playground/src/features/todos/reducer.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,10 @@ export default combineReducers<TodosState, TodosAction>({
1919
return [...state, action.payload];
2020

2121
case TOGGLE:
22-
return state.map(
23-
item =>
24-
item.id === action.payload
25-
? { ...item, completed: !item.completed }
26-
: item
22+
return state.map(item =>
23+
item.id === action.payload
24+
? { ...item, completed: !item.completed }
25+
: item
2726
);
2827

2928
default:
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { ActionType, getType } from 'typesafe-actions';
2+
3+
import { Todo } from '../features/todos/models';
4+
import * as actions from '../features/todos/actions';
5+
6+
export type TodosAction = ActionType<typeof actions>;
7+
8+
function createReducer<S, A extends { type: string }>(
9+
initialState: S,
10+
handlers: {
11+
[P in A['type']]?: A extends { type: P }
12+
? (state: S, action: A) => S
13+
: never
14+
}
15+
) {
16+
return (state: S = initialState, action: A): S => {
17+
if (handlers.hasOwnProperty(action.type)) {
18+
return (handlers as any)[action.type](state, action);
19+
} else {
20+
return state;
21+
}
22+
};
23+
}
24+
25+
export const todos = createReducer<Todo[], TodosAction>([], {
26+
['todos/ADD' as 'todos/ADD']: (state, action) => {
27+
return [...state, action.payload];
28+
},
29+
['todos/TOGGLE']: (state, action) => {
30+
return state.map(item =>
31+
item.id === action.payload
32+
? { ...item, completed: !item.completed }
33+
: item
34+
);
35+
},
36+
});

0 commit comments

Comments
 (0)