Skip to content

Commit

Permalink
fix(example): optimistically add/remove book from collection (#2429)
Browse files Browse the repository at this point in the history
Closes #2417
  • Loading branch information
AdditionAddict authored Mar 11, 2020
1 parent dfb2787 commit b0aacf7
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions projects/example-app/src/app/books/reducers/collection.reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createReducer, on } from '@ngrx/store';
import {
CollectionApiActions,
CollectionPageActions,
SelectedBookPageActions,
} from '@example-app/books/actions';

export const collectionFeatureKey = 'collection';
Expand Down Expand Up @@ -30,9 +31,15 @@ export const reducer = createReducer(
loading: false,
ids: books.map(book => book.id),
})),
// Supports handing multiple types of actions
/**
* Optimistically add book to collection.
* If this succeeds there's nothing to do.
* If this fails we revert state by removing the book.
*
* `on` supports handling multiple types of actions
*/
on(
CollectionApiActions.addBookSuccess,
SelectedBookPageActions.addBook,
CollectionApiActions.removeBookFailure,
(state, { book }) => {
if (state.ids.indexOf(book.id) > -1) {
Expand All @@ -44,8 +51,12 @@ export const reducer = createReducer(
};
}
),
/**
* Optimistically remove book from collection.
* If addBook fails, we "undo" adding the book.
*/
on(
CollectionApiActions.removeBookSuccess,
SelectedBookPageActions.removeBook,
CollectionApiActions.addBookFailure,
(state, { book }) => ({
...state,
Expand Down

0 comments on commit b0aacf7

Please sign in to comment.