diff --git a/packages/react/src/utils/changes.ts b/packages/react/src/utils/changes.ts index f00fa7b3..6de98e3a 100644 --- a/packages/react/src/utils/changes.ts +++ b/packages/react/src/utils/changes.ts @@ -19,11 +19,11 @@ function applyChanges(changes: any[], elements: any[]): any[] { // By storing a map of changes for each element, we can a quick lookup as we // iterate over the elements array! const changesMap = new Map(); - const newItems: any[] = []; + const addItemChanges: any[] = []; for (const change of changes) { if (change.type === 'add') { - newItems.push(change); + addItemChanges.push(change); continue; } else if (change.type === 'remove' || change.type === 'replace') { // For a 'remove' change we can safely ignore any other changes queued for @@ -74,9 +74,15 @@ function applyChanges(changes: any[], elements: any[]): any[] { updatedElements.push(updatedElement); } - if (newItems.length) { - newItems.forEach((item) => { - updatedElements.splice(item.index, 0, { ...item.item }); + // we need to wait for all changes to be applied before adding new items + // to be able to add them at the correct index + if (addItemChanges.length) { + addItemChanges.forEach((change) => { + if (change.index !== undefined) { + updatedElements.splice(change.index, 0, { ...change.item }); + } else { + updatedElements.push({ ...change.item }); + } }); }