Select a Variation
Learn how to validate variation selections, resolve the correct child product using the variation matrix, and add it to cart with proper error handling.
Selection Flow
1. Validate All Options Selected
Before resolving a child product, ensure all variations have selections:
function validateSelections(
selectedOptions: Record<string, string>,
variations: Variation[]
): { isValid: boolean; missing: string[] } {
const missing = variations
.filter(v => !selectedOptions[v.id])
.map(v => v.name);
return {
isValid: missing.length === 0,
missing
};
}
// Example usage
const validation = validateSelections(selectedOptions, variations);
if (!validation.isValid) {
return { error: `Please select: ${validation.missing.join(', ')}` };
}
2. Resolve Child Product
Use the variation matrix to find the child product ID:
import { getSkuIdFromOptions } from '@/utils/product-helper';
// Collect selected option IDs in order
const optionIds = Object.values(selectedOptions);
// Look up child product ID
const childId = getSkuIdFromOptions(optionIds, variationMatrix);
if (!childId) {
return { error: 'This combination is not available' };
}
info
See Understanding the Variation Matrix for the getSkuIdFromOptions
implementation.
3. Add to Cart
Add the resolved child product to cart using the SDK:
import { manageCarts, getCartId } from '@epcc-sdk/sdks-shopper';
const cartId = getCartId();
await manageCarts({
path: { cartID: cartId },
body: {
data: {
type: 'cart_item',
id: childId, // Must be child product ID, not parent!
quantity: 1
}
}
});
Key Points
- Validate first - Check all options are selected before lookup
- Child ID only - Never attempt to add parent product to cart
- Handle errors - Invalid combinations and out of stock scenarios
- Loading states - Show feedback during async operations
- Inventory checks - Optional but recommended for better UX
Next Steps
With selection implemented:
- Choose a UI pattern: See Variation Selection Patterns
- Manage the cart: Continue to Cart Management