Skip to content

Adding an observer to a query causes it to ignore its enabled prop #2502

@thclark

Description

@thclark

Describe the bug

Adding an observer to a query causes it to ignore its enabled prop.

Initially asked here, it's had no answers and one upvote so I'm beginning to suspect it's not just me being dumb.

To Reproduce

I took a pretty straightforward query:

const refreshable = false // hard coded for the sake of example
const tokenQuery = useQuery('refresh-token', whateverQueryFn, {
  enabled: refreshable,
  refetchInterval: 1000 * 30,
  refetchIntervalInBackground: true,
})

If this is stand-alone then no problems. Everything initialises, and unless refreshable is set true then it lies dormant. However, in the same hook if you then add an observer...

useEffect(() => {
  // Create an observer to watch the query and update its result into state
  const observer = new QueryObserver(queryClient, {
    queryKey: 'refresh-token',
  })
  const unsubscribe = observer.subscribe((queryResult) => {
    console.log(
      'Do something with the token!'
      queryResult.data
    )
  })

  // Clean up the subscription when the component unmounts
  return () => {
    unsubscribe()
  }
}, [token, queryClient])

Attaching the observer causes a fetch (and failure, and multiple retries) to happen irrespective of the value of enabled.

Expected behavior
I think an observed query should respect the value of the enabled parameter.

Screenshots
n/a

Desktop (please complete the following information):

  • OS: OSX
  • Browser: Chrome
  • Version: 91.0.4472.164 (Official Build) (arm64)

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