cal/apps/web/lib/hooks/useInViewObserver.ts
Alex van Andel ba04533de3
Linting fixes round #1 (#2906)
* Fixes round #1

* disabled any warning for intentional typing of AsyncReturnType

* Whacked MetaMask add / remove button

* types, not great, not terrible, better than any

* Fixed typo in CheckboxField and wrapped description in <label>

* Feedback

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: zomars <zomars@me.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-06-06 18:24:37 +00:00

43 lines
1018 B
TypeScript

import React from "react";
const isInteractionObserverSupported = typeof window !== "undefined" && "IntersectionObserver" in window;
export const useInViewObserver = (onInViewCallback: () => void) => {
const [node, setRef] = React.useState<HTMLElement | null>(null);
const onInViewCallbackRef = React.useRef(onInViewCallback);
onInViewCallbackRef.current = onInViewCallback;
React.useEffect(() => {
if (!isInteractionObserverSupported) {
// Skip interaction check if not supported in browser
return;
}
let observer: IntersectionObserver;
if (node && node.parentElement) {
observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
onInViewCallbackRef.current();
}
},
{
root: document.body,
}
);
observer.observe(node);
}
return () => {
if (observer) {
observer.disconnect();
}
};
}, [node]);
return {
ref: setRef,
};
};