Ensure stable identity for pricing tiers in forms

Adds a tempId to new pricing tiers for stable mapping before backend _id assignment. Updates mapping logic in pricing-tiers form to use tempId or _id for reliable event handling and rendering.
This commit is contained in:
NotII
2025-10-16 12:12:22 +01:00
parent 577c93d62b
commit 03a2e37502
3 changed files with 19 additions and 9 deletions

View File

@@ -76,14 +76,12 @@ export const PricingTiers = ({
.sort((a, b) => (a?.minQuantity || 0) - (b?.minQuantity || 0))
.map((tier, sortedIndex) => {
if (!tier) return null;
// Find the original index for proper event handling
const originalIndex = pricing.findIndex(p =>
p === tier || (p?.minQuantity === tier?.minQuantity && p?.pricePerUnit === tier?.pricePerUnit)
);
// Prefer stable identifiers for mapping back to the original array
const keyId = tier._id || tier.tempId;
const originalIndex = pricing.findIndex((p) => (p?._id || p?.tempId) === keyId);
return (
<div
key={tier._id || originalIndex}
key={keyId || originalIndex}
className="grid grid-cols-[1fr_1fr_1fr_auto] gap-2 mt-2"
>
<Input

View File

@@ -98,7 +98,19 @@ export const ProductModal: React.FC<ProductModalProps> = ({
const handleAddTier = () => {
setProductData((prev) => ({
...prev,
pricing: [...prev.pricing, { minQuantity: 0, pricePerUnit: 0 }],
pricing: [
...prev.pricing,
{
minQuantity: 0,
pricePerUnit: 0,
// tempId ensures stable identity before backend assigns _id
// Using crypto.randomUUID if available, otherwise a timestamp fallback
tempId:
(typeof crypto !== "undefined" && (crypto as any).randomUUID
? (crypto as any).randomUUID()
: `${Date.now()}-${Math.random()}`),
},
],
}));
};