最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - observer.unobserve() in useEffect cleanup throwing error that parameter is not of type Element - Stack Overflow

programmeradmin6浏览0评论

Simple Component Example:

export default function App () {
  const videoRef = useRef();
  const onScreen = useOnScreen(videoRef, "-300px"); // hook for play/pause based on visibility
  
  <div ref={videoRef} className="h-72 my-4 rounded-2xl">
    <ReactPlayer
      url="my-recording.mov"
      loop
      playing={onScreen ? true : false}  />
  </div>
}

I am using the useOnScreen hook from here: /

The hook works fine when running but when I change page by clicking a link using react-router-dom it throws the following error:

TypeError: Failed to execute 'unobserve' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

I think the problem is in the cleanup of useEffect function (maybe the ref is already unmounted when cleanup starts to run therefore ref.current is null):

return () => {
  observer.unobserve(ref.current); // here ref.current might be null
};

It works properly if I add a check before calling unobserve:

return () => {
  if (ref.current) {
    observer.unobserve(ref.current);
  }
};

But I am not sure if this will leave the observer running and waste resources.

Please provide a solution that works and is also efficient.

Simple Component Example:

export default function App () {
  const videoRef = useRef();
  const onScreen = useOnScreen(videoRef, "-300px"); // hook for play/pause based on visibility
  
  <div ref={videoRef} className="h-72 my-4 rounded-2xl">
    <ReactPlayer
      url="my-recording.mov"
      loop
      playing={onScreen ? true : false}  />
  </div>
}

I am using the useOnScreen hook from here: https://usehooks./useOnScreen/

The hook works fine when running but when I change page by clicking a link using react-router-dom it throws the following error:

TypeError: Failed to execute 'unobserve' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

I think the problem is in the cleanup of useEffect function (maybe the ref is already unmounted when cleanup starts to run therefore ref.current is null):

return () => {
  observer.unobserve(ref.current); // here ref.current might be null
};

It works properly if I add a check before calling unobserve:

return () => {
  if (ref.current) {
    observer.unobserve(ref.current);
  }
};

But I am not sure if this will leave the observer running and waste resources.

Please provide a solution that works and is also efficient.

Share Improve this question asked Jun 27, 2021 at 15:49 RajRaj 2,0283 gold badges31 silver badges57 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

I have faced into the same issue but solved it by using useLayoutEffect instead of useEffect in the useOnScreen hook.

发布评论

评论列表(0)

  1. 暂无评论