Providing Angular NgRx optimistic delete example
I'm preparing a concise Angular NgRx example illustrating optimistic UI updates for deleting items: removing the item from the store immediately, then calling the API via effects, rolling back on failure with a toast notification using Angular Material's MatSnackBar. The code covers actions, reducer, effects, component, and service with minimal boilerplate.
Below is a minimal Angular + NgRx example that implements optimistic deletes with rollback and a toast on failure.
Key idea:
Dispatch deleteItem with the full item as payload.
The reducer immediately removes it from state (optimistic UI).
The effect calls the API.
On success → nothing else to do.
On failure → dispatch deleteItemFailure with the original item to reinsert it, and show a toast.
Item model
ts Copy code
// src/app/models/item.model.ts
export interface Item {
id: string;
name: string;
}
Actions
ts Copy code
// src/app/store/items.actions.ts
import { createAction, props } from '@ngrx/store';
import { Item } from '../models/item.model';
export const loadItems = createAction('[Items] Load Items');
export const loadItemsSuccess = createAction(
'[Items] Load Items Success',
props<{ items: Item[] }>()
);
export const loadItemsFailure = createAction(
'[Items] Load Items Failure',
props<{ error: any }>()
);
export const deleteItem = createAction(
'[Items] Delete Item (Optimistic)',
props<{ item: Item }>()
);
export const deleteItemSuccess = createAction(
'[Items] Delete Item Success',
props<{ id: string }>()
);
export const deleteItemFailure = createAction(
'[Items] Delete Item Failure (Rollback)',
props<{ item: Item; error: any }>()
);
Reducer (optimistic removal + rollback)
ts Copy code
// src/app/store/items.reducer.ts
import { createReducer, on } from '@ngrx/store';
import * as ItemsActions from './items.actions';
import { Item } from '../models/item.model';
export interface ItemsState {
items: Item[];
loading: boolean;
error?: any;
}
export const initialState: ItemsState = {
items: [],
loading: false,
};
export const itemsReducer = createReducer(
initialState,
on(ItemsActions.loadItems, (state) => ({ ...state, loading: true })),
on(ItemsActions.loadItemsSuccess, (state, { items }) => ({
...state,
items,
loading: false,
})),
on(ItemsActions.loadItemsFailure, (state, { error }) => ({
...state,
loading: false,
error,
})),
// Optimistic removal
on(ItemsActions.deleteItem, (state, { item }) => ({
...state,
items: state.items.filter((i) => i.id !== item.id),
})),
// Success: state already updated, nothing to change
on(ItemsActions.deleteItemSuccess, (state) => ({ ...state })),
// Rollback on failure
on(ItemsActions.deleteItemFailure, (state, { item }) => ({
...state,
items: [...state.items, item], // optionally sort if you care about order
}))
);
Selectors
ts Copy code
// src/app/store/items.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { ItemsState } from './items.reducer';
export const selectItemsState = createFeatureSelector<ItemsState>('items');
export const selectAllItems = createSelector(
selectItemsState,
(state) => state.items
);
export const selectItemsLoading = createSelector(
selectItemsState,
(state) => state.loading
);
Service (API)
ts Copy code
// src/app/services/items.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Item } from '../models/item.model';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ItemsService {
private baseUrl = 'https://example.com/api/items'; // replace with real API
constructor(private http: HttpClient) {}
getAll(): Observable<Item[]> {
return this.http.get<Item[]>(this.baseUrl);
}
delete(id: string): Observable<void> {
return this.http.delete<void>(`${this.baseUrl}/${id}`);
}
}
Effects (API call + rollback + toast)
ts Copy code
// src/app/store/items.effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { MatSnackBar } from '@angular/material/snack-bar';
import { of } from 'rxjs';
import { catchError, map, mergeMap, tap } from 'rxjs/operators';
import * as ItemsActions from './items.actions';
import { ItemsService } from '../services/items.service';
@Injectable()
export class ItemsEffects {
constructor(
private actions$: Actions,
private itemsService: ItemsService,
private snackBar: MatSnackBar
) {}
loadItems$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.loadItems),
mergeMap(() =>
this.itemsService.getAll().pipe(
map((items) => ItemsActions.loadItemsSuccess({ items })),
catchError((error) => of(ItemsActions.loadItemsFailure({ error })))
)
)
)
);
deleteItem$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.deleteItem),
mergeMap(({ item }) =>
this.itemsService.delete(item.id).pipe(
// Success, nothing extra to do
map(() => ItemsActions.deleteItemSuccess({ id: item.id })),
// On failure, rollback
catchError((error) =>
of(ItemsActions.deleteItemFailure({ item, error }))
)
)
)
)
);
deleteItemFailureToast$ = createEffect(
() =>
this.actions$.pipe(
ofType(ItemsActions.deleteItemFailure),
tap(() =>
this.snackBar.open('Delete failed. Rolled back.', 'OK', {
duration: 3000,
})
)
),
{ dispatch: false }
);
}
Component (list with delete)
ts Copy code
// src/app/items/items.component.ts
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Item } from '../models/item.model';
import * as ItemsSelectors from '../store/items.selectors';
import * as ItemsActions from '../store/items.actions';
@Component({
selector: 'app-items',
templateUrl: './items.component.html',
})
export class ItemsComponent implements OnInit {
items$: Observable<Item[]> = this.store.select(ItemsSelectors.selectAllItems);
loading$: Observable<boolean> = this.store.select(
ItemsSelectors.selectItemsLoading
);
constructor(private store: Store) {}
ngOnInit(): void {
this.store.dispatch(ItemsActions.loadItems());
}
delete(item: Item): void {
// Optimistic delete (removes immediately)
this.store.dispatch(ItemsActions.deleteItem({ item }));
}
}
html Copy code
<!-- src/app/items/items.component.html -->
<div *ngIf="loading$ | async">Loading…</div>
<ul>
<li *ngFor="let item of (items$ | async)">
{{ item.name }}
<button (click)="delete(item)">Delete</button>
</li>
</ul>
Module wiring (NgRx + Material)
ts Copy code
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { AppComponent } from './app.component';
import { ItemsComponent } from './items/items.component';
import { itemsReducer } from './store/items.reducer';
import { ItemsEffects } from './store/items.effects';
@NgModule({
declarations: [AppComponent, ItemsComponent],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
MatSnackBarModule,
StoreModule.forRoot({ items: itemsReducer }),
EffectsModule.forRoot([ItemsEffects]),
],
bootstrap: [AppComponent],
})
export class AppModule {}
Flow recap:
User clicks “Delete”.
deleteItem({ item }) dispatched → reducer removes from state immediately (optimistic UI).
Effect calls API DELETE /items/:id.
On success: deleteItemSuccess (no state change needed).
On failure: deleteItemFailure({ item, error }) → reducer re-adds the item (rollback) and effect shows a toast.
That’s it! This gives a snappy UI with rollback and user feedback on failure.