How to disable re-calling API after onClick and execute refetch the react-query hook?

Viewed 989

for example, i've a component to fetch and call an API, but that query by default is enabled: false and i should fire that by onClick:

const query = useQuery('key', fetch, { enabled: false })

const exec = () => query.refetch()

return <button onClick={exec}>Load</button>

But i've a new API call after every clicks on the button, actually i want to cancel re-calling the API still the cached data is available and is not stale...

I there any way to implement something like refetch to retrieve cached data but without re-calling the API? our basically react-query has a re-call for any data reteive?

in fact, our data doesn't change frequently and is fix for 2-3 days...

other words, our clients frequently work with nested drop-downs with same API calls and i want to reduce same key queries... imagine that, something like category to select a brand for products

Thanks

2 Answers

imagine that, something like category to select a brand for products

This is a classic example for react-query where you want to put all dependencies of your query into your cache key (see the official docs). That way, the caches won't override each other, and you'll instantly get the values back from the cache if they are available. Not that you will also get a background refetch, and that's where staleTime comes in. If you don't want that, set a higher staleTime to only retrieve the value from the cache if it exists.

To illustrate, let's take your example of a select of categories for products:

function MyComponent() {
  const [category, setCategory] = useState(null)
  
  const { data } = useQuery(['key', category], () => fetchProducts(category), { enabled: !!brand, staleTime: 1000 * 60 * 3 })

  <CategorySelect onSelect={setCategory} />
}

Multiple things going on here:

  1. I have some local state, where I store the selected category
  2. This selection drives the query. The query is disabled as long as I have no selection, but enables once the user makes a selection
  3. every time the category changes, the query key changes, which will make react-query trigger a refetch automatically, for the new data
  4. I've set the staleTime to 3 minutes. If I chose a category that I have already chosen, I will get data from the cache. Within 3 minutes, I will only get it from the cache. If my data is older, I will get it from the cache and the data will also be updated in the background.
Related