TanStack / query

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
https://tanstack.com/query
MIT License
40.54k stars 2.73k forks source link

Docs: Error on window.removeEventListener of focusManager #7391

Closed Oc1S closed 1 month ago

Oc1S commented 1 month ago

Describe the bug

Docs on https://tanstack.com/query/v5/docs/framework/react/guides/window-focus-refetching#custom-window-focus-event is a misusage of window.removeEventListener

focusManager.setEventListener((handleFocus) => {
  // Listen to visibilitychange
  if (typeof window !== 'undefined' && window.addEventListener) {
    window.addEventListener('visibilitychange', () => handleFocus(), false)
                                                ^^^^^^^^^^^^^^^^^^^
                                                Create an instance as callback here
    return () => {
      // Be sure to unsubscribe if a new handler is set
      window.removeEventListener('visibilitychange', () => handleFocus())
                                                     ^^^^^^^^^^^^^^^^^^^
                                                     Another function instance here, removeEventListener on 
                                                     this instance won't remove the eventListener above👆
    }
  }
})

Your minimal, reproducible example

https://tanstack.com/query/v5/docs/framework/react/guides/window-focus-refetching#custom-window-focus-event

Steps to reproduce

Go to the page below. 👇 https://tanstack.com/query/v5/docs/framework/react/guides/window-focus-refetching#custom-window-focus-event

Expected behavior

We can create a event handler like this 👇

focusManager.setEventListener((handleFocus) => {
  // Listen to visibilitychange
  if (typeof window !== 'undefined' && window.addEventListener) {
    /** create an instance here **/
    const visibilitychangeHandler = () => {
      document ? handleFocus(document.visibilityState === 'visible' ) : handleFocus()
    }
    window.addEventListener('visibilitychange', visibilitychangeHandler, false)
    return () => {
      // Be sure to unsubscribe if a new handler is set
      window.removeEventListener('visibilitychange', visibilitychangeHandler)
    }
  }
})

so that we can removeEventListener correctly

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

Any browser

Tanstack Query adapter

None

TanStack Query version

5

TypeScript version

No response

Additional context

No response