Home > widget-integration > CartService > restoreCartIfNeeded

CartService.restoreCartIfNeeded() method

Restore cart from localStorage backup if backup exists Handles cart recovery scenarios (after checkout, session restore, etc.)

Process: 1. Check for backup_cart_items in localStorage 2. If found, clear current cart 3. Add all backed up items back to cart 4. Clean up backup (success or failure)

Override to customize backup/restore logic or add validation

Signature:

restoreCartIfNeeded(): Promise<void>;

Returns:

Promise<void>

Promise that resolves when restore is complete or no backup exists

Example

Add validation before restore

async restoreCartIfNeeded(): Promise<void> {
  const backup = localStorage.getItem('backup_cart_items');
  if (!backup) return;

  try {
    const items = JSON.parse(backup);

    // Validate items are still available
    const validItems = await this.validateBackupItems(items);

    if (validItems.length === 0) {
      this.showMessage('Backed up items are no longer available');
      return;
    }

    await this.cartAPI.clearCart();
    await this.cartAPI.addMultiProductToCart(validItems);

    this.showMessage(`Restored ${validItems.length} items to cart`);
  } catch (error) {
    this.appService.logger.error('Failed to restore cart:', error);
  } finally {
    localStorage.removeItem('backup_cart_items');
  }
}