apollographql / apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
Other
130 stars 7 forks source link

Support "debounce" as option within useQuery #219

Open dannycochran opened 4 years ago

dannycochran commented 4 years ago

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
christo8989 commented 3 years ago

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
}
david-morris commented 6 months ago

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.