apollo-feature-requests icon indicating copy to clipboard operation
apollo-feature-requests copied to clipboard

Support "debounce" as option within useQuery

Open dannycochran opened this issue 4 years ago • 2 comments

Similar to the Apollo Vue client, support a debounce option within useQuery:

https://v4.apollo.vuejs.org/api/use-query.html#parameters

There was an issue filed here as a bug that was closed:

https://github.com/apollographql/react-apollo/issues/450#issuecomment-298821902

This would be a great recipe and/or an external package. I don't think it should be in the core RA though!

I think this is worth supporting natively, as a lot of the solutions to work around this put a lot of onus on the consumer:

  1. debouncing state or props and using that for your variables
  2. high order component to debounce props
  3. some type of middleware HTTP link

dannycochran avatar Apr 01 '20 16:04 dannycochran

Here's my hack for a single query (not much use if you need a generic solution across your app)...

Not great but maybe worth showing. Also, maybe this is more like throttling so update as needed.

Also, not sure if milliseconds is accurate...

const requestTimestamp = Date.now()
const debounceQuery = (query, milliseconds) => () => {
  if (query.data) {
    const delta = Date.now() - requestTimestamp
    if (delta > milliseconds) {
      requestTimestamp = Date.now()
      query.refetch()
    }
  }
}

const useSomeHook = () => {
  const query = useQuery(GQL)
  useEffect(debounceQuery(query, 1000))
  return query
}

christo8989 avatar Mar 04 '21 00:03 christo8989

This would add functionality that doesn't exist right now.

I would love to see debounces on variable change, BUT only if there's a cache miss. That way, a user who's already fetched the data doesn't need to wait for a debounce cycle to hit that cache.

If we had fine grained control, that has advantages too. For example, I'd like to debounce text fields but not checkboxes.

I suggest a simple use case: paged search query.

  • A good solution should fetch the next page immediately

  • A good solution should return data found in cache immediately

  • A good solution should debounce a fetch due to hook option object variables

  • Bonus: can you set different debounce times for different variables?

david-morris avatar Apr 30 '24 15:04 david-morris