Hi i'm making an infinite scroll event to trigger new fetch on React Query, the problem is that i can't find a way to type this on typescript
function onScroll(this: Document, ev: ScrollBehavior<EventListener>) {
const { scrollHeight, scrollTop, clientHeight } = ev.target.scrollingElement;
if (hasNextPage && scrollHeight - scrollTop <= clientHeight * 1.2) {
fetchNextPage();
}
}
CodePudding user response:
event.target
will never be document
, you have to access document
directly
function onScroll() {
const { scrollHeight, scrollTop, clientHeight } = document.scrollingElement;
if (hasNextPage && scrollHeight - scrollTop <= clientHeight * 1.2) {
fetchNextPage();
}
}
CodePudding user response:
For those who are searching for this, the solution was to type event.target as Document like this:
function onScroll(ev: Event) {
const target = ev.target as Document;
const { scrollHeight, scrollTop, clientHeight } = target.scrollingElement;
if (hasNextPage && scrollHeight - scrollTop <= clientHeight * 1.2) {
fetchNextPage();
}
}
document.addEventListener('scroll', onScroll);
return () => {
document.removeEventListener('scroll', onScroll);
};