fix: Array sync issues when source array is shorter than target #618
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #468
Problem
When merging arrays in
mergeIntoObservable, the code only iterated over source array indices. If the source array was shorter than the target, extra elements in the target were never removed.This caused real-time sync issues across multiple devices/browsers - removing array items would update correctly in the database and locally, but other connected clients would not see the removal.
Why it only affected multi-device sync
With a single browser, the local optimistic update masks the bug. The second browser relies solely on the incoming realtime update, exposing the failure to apply array changes.
Example
// Before fix (broken):
const target = observable({ arr: ['a', 'b', 'c'] });
mergeIntoObservable(target, { arr: ['a'] });
target.arr.get(); // ['a', 'b', 'c'] ❌ extra elements remain
// After fix:
target.arr.get(); // ['a'] ✅## Solution
set()to ensure correct lengthSparse array detection:
Object.keys(arr).length < arr.lengthBackwards compatibility
Sparse array behavior is preserved - partial index updates (e.g.,
arr[5] = 'x') still merge correctly without affecting other indices.