[英]How to disable re-calling API after onClick and execute refetch the react-query hook?
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:例如,我有一个组件来获取和调用 API,但默认情况下该查询是
enabled: false
,我应该通过 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...但是每次点击按钮后我都有一个新的 API 调用,实际上我想取消重新调用 API 仍然缓存数据可用并且不是过时的......
I there any way to implement something like refetch to retrieve cached data but without re-calling the API?我有什么方法可以实现诸如 refetch 之类的东西来检索缓存数据但不重新调用 API? our basically react-query has a re-call for any data reteive?
我们基本上反应查询有重新调用任何数据 reteive?
in fact, our data doesn't change frequently and is fix for 2-3 days...事实上,我们的数据不会经常更改,并且会修复 2-3 天...
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换句话说,我们的客户经常使用具有相同 API 调用的嵌套下拉菜单,我想减少相同的关键查询......想象一下,像类别一样为产品选择品牌
Thanks谢谢
You can set staleTime
and cacheTime
options of your query to Infinity
to keep your cache always available您可以将查询的
staleTime
和cacheTime
选项设置为Infinity
以保持缓存始终可用
https://react-query.tanstack.com/reference/useQuery https://react-query.tanstack.com/reference/useQuery
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 ).这是 react-query 的一个经典示例,您希望将查询的所有依赖项放入缓存键中(请参阅官方文档)。 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.并不是说您还会获得后台重新获取,这就是
staleTime
用武之地。如果您不想要那样,请设置更高的 staleTime 以仅从缓存中检索值(如果存在)。
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:这里发生了很多事情:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.