import { useHost } from "@saasquatch/component-boilerplate";
import { useMemo, useState } from "@saasquatch/universal-hooks";
export function useChildElements() {
  const host = useHost();
  const initialState = host.children.length
    ? Array.from(host.children)
    : [];
  const [childElements, setChildElements] = useState(initialState);
  let observer;
  // Create observer once
  useMemo(() => {
    observer = new MutationObserver(() => {
      const children = Array.from(host.children);
      setChildElements([...children]);
    });
  }, []);
  // Listen to host and observe / disconnect
  useMemo(() => {
    if (!observer)
      return;
    observer.observe(host, { childList: true });
    return () => {
      observer.disconnect();
    };
  }, [host]);
  return childElements;
}
