Skip to content

Commit

Permalink
fix(observer): fix of reobserve doesn't add observer to map
Browse files Browse the repository at this point in the history
When new element already holds a ref to an observer
and the previous element (that used the same observer) unobserves,
it creates a broken state when that observer is deleted from map,
but new element holds that ref and thinks it's ok to observe

Essentially i'm bringing back part of the code deleted in #153, namely https://github.com/researchgate/react-intersection-observer/pull/153/files#diff-44cb04e2627c3ab84281b41d14880e5e822437f19144e8c14a6c95f7f7fa14bbL72

I also added tests to not to break this and #153 in the future
  • Loading branch information
saitonakamura authored and danez committed Nov 4, 2020
1 parent ba9cac5 commit 3ce4536
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ export function createObserver(
}

export function observeElement(element: Instance) {
if (element.observer && !observerElementsMap.has(element.observer)) {
observerElementsMap.set(element.observer, new Set<Instance>());
}
observerElementsMap.get(element.observer)?.add(element);
element.observer!.observe(element.target!);
}
Expand Down
16 changes: 16 additions & 0 deletions test/unit/observer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,20 @@ describe('findObserverElement', () => {
expect(instance1).toEqual(entry1);
expect(instance2).toEqual(entry2);
});

test('two subsequent createObserver calls should not produce two observers', () => {
const observer1 = createObserver();
const observer2 = createObserver();
expect(observer1).toEqual(observer2);
});

test('observing element should add target to observerElementsMap even if there is no such observer key', () => {
const observer = createObserver();
const entry = { observer, target: target1 };
observeElement(entry);
unobserveElement(entry, entry.target);
observeElement(entry);
const instance = findObserverElement(observer, entry);
expect(instance).toEqual(entry);
});
});

0 comments on commit 3ce4536

Please sign in to comment.