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
You can set staleTime and cacheTime options of your query to Infinity to keep your cache always available
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: