Skip to content

Commit b0aacf7

Browse files
fix(example): optimistically add/remove book from collection (#2429)
Closes #2417
1 parent dfb2787 commit b0aacf7

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

projects/example-app/src/app/books/reducers/collection.reducer.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { createReducer, on } from '@ngrx/store';
33
import {
44
CollectionApiActions,
55
CollectionPageActions,
6+
SelectedBookPageActions,
67
} from '@example-app/books/actions';
78

89
export const collectionFeatureKey = 'collection';
@@ -30,9 +31,15 @@ export const reducer = createReducer(
3031
loading: false,
3132
ids: books.map(book => book.id),
3233
})),
33-
// Supports handing multiple types of actions
34+
/**
35+
* Optimistically add book to collection.
36+
* If this succeeds there's nothing to do.
37+
* If this fails we revert state by removing the book.
38+
*
39+
* `on` supports handling multiple types of actions
40+
*/
3441
on(
35-
CollectionApiActions.addBookSuccess,
42+
SelectedBookPageActions.addBook,
3643
CollectionApiActions.removeBookFailure,
3744
(state, { book }) => {
3845
if (state.ids.indexOf(book.id) > -1) {
@@ -44,8 +51,12 @@ export const reducer = createReducer(
4451
};
4552
}
4653
),
54+
/**
55+
* Optimistically remove book from collection.
56+
* If addBook fails, we "undo" adding the book.
57+
*/
4758
on(
48-
CollectionApiActions.removeBookSuccess,
59+
SelectedBookPageActions.removeBook,
4960
CollectionApiActions.addBookFailure,
5061
(state, { book }) => ({
5162
...state,

0 commit comments

Comments
 (0)