Reputation: 1205
I'm using React with hooks, I'm trying to create a custom hook for interaction Observer
For this feature here: Infinite Scroll in react
Since I want for it to be reused multiple times, I want to use it for posts, commments etc
Here is whta I got so far:
useObserver hook:
import React, { useState, useEffect } from 'react';
const useObserver = ({ element, callback }) => {
const [page, setPage] = useState(1);
console.log('props');
console.log(page);
const options = {
root: null,
rootMargin: '0px',
threshold: 1.0
};
const observerHandler = (entities) => {
console.log('handle observer');
const y = entities[0].boundingClientRect.y;
const target = entities[0];
if (target.isIntersecting) {
setPage((counter) => counter + 1);
}
};
useEffect(() => {
const observer = new IntersectionObserver(observerHandler, options);
if (element.current) {
observer.observe(element.current);
}
});
return [1];
};
export default useObserver;
Parent Component where I use hook:
import React, { useRef, useState, useEffect } from 'react';
import useObserver from './useObserver';
const Posts = ({ posts }) => {
// initiate posts loader
const loader = useRef(null);
const [page] = useObserver({ element: loader });
return (
<div id="post-list">
<h1> Post list </h1>
<div class="test" ></div>
<h1>Show posts</h1>
<div className="loading" ref={loader}>
<h1>Loader</h1>
</div>
</div>
);
};
The problem that I'm having is that state page inside of useObserver component get increment always and gets called muliple time continuously, but it should be called only once when user scrolls till that component
Upvotes: 0
Views: 131
Reputation: 153
try keeping an array with element in useEffect
useEffect(() => {
const observer = new IntersectionObserver(observerHandler, options);
if (element.current) {
observer.observe(element.current);
}
},[element]); //when you specify an empty array it runs only once, an array with value will run when ever the value changes
Upvotes: 1