Skip to content

Commit 78ca80c

Browse files
committed
Merge pull request #529 from rackt/fix-todomvc
Find next todo ID correctly. Fixes #524
2 parents 035001f + 408941a commit 78ca80c

File tree

3 files changed

+59
-2
lines changed

3 files changed

+59
-2
lines changed

docs/recipes/WritingTests.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export default function todos(state = initialState, action) {
7979
switch (action.type) {
8080
case ADD_TODO:
8181
return [{
82-
id: state.length,
82+
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
8383
completed: false,
8484
text: action.text
8585
}, ...state];

examples/todomvc/reducers/todos.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export default function todos(state = initialState, action) {
1111
switch (action.type) {
1212
case ADD_TODO:
1313
return [{
14-
id: state.length,
14+
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
1515
completed: false,
1616
text: action.text
1717
}, ...state];

examples/todomvc/test/reducers/todos.spec.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,33 @@ describe('todos reducer', () => {
4545
completed: false,
4646
id: 0
4747
}]);
48+
49+
expect(
50+
todos([{
51+
text: 'Run the tests',
52+
completed: false,
53+
id: 1
54+
}, {
55+
text: 'Use Redux',
56+
completed: false,
57+
id: 0
58+
}], {
59+
type: types.ADD_TODO,
60+
text: 'Fix the tests'
61+
})
62+
).toEqual([{
63+
text: 'Fix the tests',
64+
completed: false,
65+
id: 2
66+
}, {
67+
text: 'Run the tests',
68+
completed: false,
69+
id: 1
70+
}, {
71+
text: 'Use Redux',
72+
completed: false,
73+
id: 0
74+
}]);
4875
});
4976

5077
it('should handle DELETE_TODO', () => {
@@ -185,4 +212,34 @@ describe('todos reducer', () => {
185212
id: 0
186213
}]);
187214
});
215+
216+
it('should not generate duplicate ids after CLEAR_COMPLETED', () => {
217+
expect(
218+
[{
219+
type: types.COMPLETE_TODO,
220+
id: 0
221+
}, {
222+
type: types.CLEAR_COMPLETED
223+
}, {
224+
type: types.ADD_TODO,
225+
text: 'Write more tests'
226+
}].reduce(todos, [{
227+
id: 0,
228+
completed: false,
229+
text: 'Use Redux'
230+
}, {
231+
id: 1,
232+
completed: false,
233+
text: 'Write tests'
234+
}])
235+
).toEqual([{
236+
text: 'Write more tests',
237+
completed: false,
238+
id: 2
239+
}, {
240+
text: 'Write tests',
241+
completed: false,
242+
id: 1
243+
}]);
244+
});
188245
});

0 commit comments

Comments
 (0)