I have this issue where I want to know in real-time the number of li element that are getting added to the ul, I am using a custom observer hook the problem is it does not seem to be working.. any idea what I am doing wrong? , I don’t want the number to show when for example if I add to the list I want to implement some logic when the items are getting rendered on load, and if the count reaches for example 10 I want for sake of argument insert a div between the li and the following li.
const listRef = useRef<HTMLUListElement>(null);
const [count, setCount] = useState(0);
const onListMutation = useCallback(
(mutationList) => {
console.log(mutationList);
setCount(mutationList[0].target.children.length);
console.log(mutationList);
},
[setCount]
);
const DEFAULT_OPTIONS = {
config: { attributes: true, childList: true, subtree: true },
};
const useMutationObservabl = (targetEl: any, cb: any, options: any) => {
const [observer, setObserver] = useState<any>(null);
useEffect(() => {
const { debounceTime } = options;
const obs = new MutationObserver(cb);
setObserver(obs!);
}, [cb, options, setObserver]);
useEffect(() => {
if (!observer) return;
const { config } = options;
observer.observe(targetEl, config);
return () => {
if (observer) {
observer.disconnect();
}
};
}, [observer, targetEl, options]);
};
useMutationObservabl(listRef.current!, onListMutation, DEFAULT_OPTIONS);
return (
<div id='Items' style={{ textAlign: 'center' }}>
itemscol.map(([groupName, items]: Mapped) => (
<ul
ref={listRef}
>
{Name}
</ul>
{items.map((exercise) => (
<li>
{Name}
</li>
))}
</Container>
))}
</div>
);
};
export default BodyExport;