Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
pahhh-blo opened this issue Sep 28, 2021 · 2 comments
Labels
example Changes related to examples

Comments

@pahhh-blo
Copy link

Bug report

Description / Observed Behavior

What kind of issues did you encounter with SWR?

When attempting to use the useSWRInfinite hook by following the example, I get a type error coming from the useOnScreen hook.

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

observer.observe(ref.current)

// node_modules/tyepscript/lib/lib.dom.d.ts
interface IntersectionObserver {
    ...
    observe(target: Element): void;
    ....
}

This is where the problem is coming from. The Element type doesn't have a current attribute.

// node_modules/tyepscript/lib
declare var Element: {
    prototype: Element;
    new(): Element;
};

How would I go about solving this type issue?

Expected Behavior

How did you expect SWR to behave here?

I expected SWR to fetch initial data.

@pahhh-blo
Copy link
Author

I got around this issue by utilizing react-intersection-observer.

// Modified example
// https://github.com/vercel/swr/blob/master/examples/infinite-scroll/pages/index.js
...
import fetcher from '../libs/fetch'
import { useInView } from 'react-intersection-observer'

...

export default function App() {
   ...

   const { ref, inView } = useInView()
   
   ...

  useEffect(() => {
    if (inView && !isReachingEnd && !isRefreshing) {
      setSize(size + 1)
    }
  }, [inView, isRefreshing])

  return (
    <div style={{ fontFamily: 'sans-serif' }}>
      ...
      <div ref={ref}>
        {isLoadingMore ? 'loading...' : isReachingEnd ? 'no more issues' : ''}
      </div>
    </div>
  )
}

@huozhi huozhi added the example Changes related to examples label Sep 28, 2021
@huozhi
Copy link
Member

huozhi commented Sep 28, 2021

Hi @diegoramosxyz I cannot repro with the example on chrome/safari/firefox. Could you provide more information about the browser you're using?

Does adding a checking condition in useOnScreen hook works for you? like

// useOnScreen.js
export default function useOnScreen(ref) {
  const [isIntersecting, setIntersecting] = useState(false)

  useEffect(() => {
+    if (!ref.current) return

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
example Changes related to examples
Projects
None yet
Development

No branches or pull requests

3 participants