reactjsreact-hooksreact-custom-hooks

Invoke custom hook after the component is mounted


I'm trying to use useObserver hook to make endless pagination but when I pass first parameter which is the loader I get an error "Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'." because I render this element conditionally. Here is my code:

//At first I fetch data from external API
const lastElement = useRef();

useObserver(lastElement, callback, dependecies)

return (
<section>
{here is mapping of data}
 {!loading && !isSearched && limit <= data.length && (
          <div ref={lastElement}><Loader/></div>
 )}
</section>

useObserver.js

export default function useObserver(ref, callback, dependecies) {
    const observer = useRef();

    useEffect(() => {
       function observerCallback(entries) {
           if(entries[0].isIntersecting) {
              callback()
           }
       }
   
      observer.current = new IntersectionObserver(observerCallback);
      observer.current.observe(ref?.current);
   
      return () => {
        observer.current.disconnect();
      }
     }, [dependecies])
}

How can I invoke this hook after the page is mounted, is there a way?


Solution

  • Have you tried moving the rendering condition into the div, so it's always rendered and only the loader is conditional?

    return (
      <section>
        {here is mapping of data}
        <div ref={lastElement}>
          {!loading && !isSearched && limit <= data.length && (
            <Loader/>
          )}
        </div>
      </section>
    )
    

    or, alternatively, not attaching the observer if the div is not present:

    export default function useObserver(ref, callback, dependecies) {
      // ...
      useEffect(() => {
        if (!ref.current) return // no action taken & no cleanup callback
        // ...
      }, [dependecies])
    }