Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(example): optimistically add/remove book from collection #2429

Merged
merged 1 commit into from
Mar 11, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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