Skip to content

Commit

Permalink
fix: observer high level DOM for changes
Browse files Browse the repository at this point in the history
  • Loading branch information
roderickhsiao committed Sep 20, 2024
1 parent b780015 commit 0938550
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-in-viewport",
"version": "1.0.0-beta.5",
"version": "1.0.0-beta.6",
"description": "Track React component in viewport using Intersection Observer API",
"author": "Roderick Hsiao <roderickhsiao@gmail.com>",
"license": "MIT",
Expand Down
25 changes: 16 additions & 9 deletions src/lib/useInViewport.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ const useInViewport = (

const enterCountRef = useRef<number>(0);
const leaveCountRef = useRef<number>(0);
// State to track when target is available
const [isTargetReady, setIsTargetReady] = useState(Boolean(target.current));

function startObserver({ observerRef }) {
const targetRef = target.current;
Expand Down Expand Up @@ -109,23 +111,28 @@ const useInViewport = (
};
}, [target.current, options, config, onEnterViewport, onLeaveViewport]);

// handles when ref changes
// Use MutationObserver to detect when `target.current` becomes non-null
// only at start up
useEffect(() => {
const currentElement = target.current;
const observerRef = observer.current;
let mutationObserver: MutationObserver | null = null;

// MutationObserver callback to check when the target ref is assigned
const handleOnChange = () => {
startObserver({
observerRef,
});
if (target.current && !isTargetReady) {
setIsTargetReady(true);
if (mutationObserver) {
mutationObserver.disconnect();
}
}
};

let mutationObserver: MutationObserver;
if (currentElement) {
setIsTargetReady(true); // If target is already available, mark it ready
} else {
// Observe changes to detect when `target.current` becomes non-null
mutationObserver = new MutationObserver(handleOnChange);

// Start observing the DOM element for mutations
mutationObserver.observe(currentElement, defaultMutationObserverOption);
mutationObserver.observe(document.body, defaultMutationObserverOption);
}

// Cleanup function to stop observing when the component unmounts
Expand Down

0 comments on commit 0938550

Please sign in to comment.