Skip to content

Docs: Error on window.removeEventListener of focusManager #7391

@Oc1S

Description

@Oc1S

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions