feat(cart): implement optimistic quantity updates with rollback on error
This commit is contained in:
@@ -43,7 +43,7 @@ export class CartComponent {
|
||||
|
||||
readonly closed = output<void>();
|
||||
|
||||
protected readonly resetKey = signal(0);
|
||||
protected readonly quantityOverrides = signal<Record<number, number>>({});
|
||||
|
||||
constructor() {
|
||||
this.quantityUpdates$.pipe(
|
||||
@@ -55,12 +55,13 @@ export class CartComponent {
|
||||
next: (res) => {
|
||||
const msg = res.message || 'Cantidad de producto actualizada.';
|
||||
this.toastService.success(msg);
|
||||
this.clearOverride(update.productVariantId);
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
console.error('Error updating cart quantity', err);
|
||||
const msg = err.error?.message || 'Error al actualizar la cantidad del producto.';
|
||||
this.toastService.danger(msg);
|
||||
this.resetKey.update(k => k + 1);
|
||||
this.clearOverride(update.productVariantId);
|
||||
}
|
||||
}),
|
||||
catchError(() => EMPTY)
|
||||
@@ -70,10 +71,29 @@ export class CartComponent {
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
protected getItemQuantity(item: CartItemMock): number {
|
||||
if (item.productVariantId !== undefined && this.quantityOverrides()[item.productVariantId] !== undefined) {
|
||||
return this.quantityOverrides()[item.productVariantId];
|
||||
}
|
||||
return item.quantity;
|
||||
}
|
||||
|
||||
private clearOverride(productVariantId: number): void {
|
||||
this.quantityOverrides.update((overrides) => {
|
||||
const copy = { ...overrides };
|
||||
delete copy[productVariantId];
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
protected onItemQuantityChange(index: number, newQuantity: number): void {
|
||||
const mockItem = this.items()[index];
|
||||
const productVariantId = mockItem?.productVariantId;
|
||||
if (productVariantId) {
|
||||
this.quantityOverrides.update((overrides) => ({
|
||||
...overrides,
|
||||
[productVariantId]: newQuantity
|
||||
}));
|
||||
this.quantityUpdates$.next({
|
||||
productVariantId,
|
||||
quantity: newQuantity
|
||||
@@ -81,6 +101,10 @@ export class CartComponent {
|
||||
} else {
|
||||
const item = this.cartService.cart()?.items[index];
|
||||
if (item) {
|
||||
this.quantityOverrides.update((overrides) => ({
|
||||
...overrides,
|
||||
[item.product_variant_id]: newQuantity
|
||||
}));
|
||||
this.quantityUpdates$.next({
|
||||
productVariantId: item.product_variant_id,
|
||||
quantity: newQuantity
|
||||
|
||||
Reference in New Issue
Block a user