From b0aacf784480da585c71081a096222552c9b9b3e Mon Sep 17 00:00:00 2001 From: AdditionAddict <48436581+AdditionAddict@users.noreply.github.com> Date: Wed, 11 Mar 2020 12:22:18 +0000 Subject: [PATCH] fix(example): optimistically add/remove book from collection (#2429) Closes #2417 --- .../app/books/reducers/collection.reducer.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/projects/example-app/src/app/books/reducers/collection.reducer.ts b/projects/example-app/src/app/books/reducers/collection.reducer.ts index 7430c64247..2a87061d2a 100644 --- a/projects/example-app/src/app/books/reducers/collection.reducer.ts +++ b/projects/example-app/src/app/books/reducers/collection.reducer.ts @@ -3,6 +3,7 @@ import { createReducer, on } from '@ngrx/store'; import { CollectionApiActions, CollectionPageActions, + SelectedBookPageActions, } from '@example-app/books/actions'; export const collectionFeatureKey = 'collection'; @@ -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) { @@ -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,