我正在使用 React Query 从 React 应用程序中的 API 获取数据。我想实现去抖以获得更好的性能,但我无法让它与 useQuery 一起使用。当我尝试将 API 调用包装在去抖函数中时,收到一条错误消息“查询函数必须返回定义的值”。
这是我当前使用的代码:
async function fetchProducts() {
const response = await axios.get(`/api/products?category_id=${category_id}&${searchParams.toString()}&page=${page}`);
return response.data;
}
const debouncedFetchProducts = React.useMemo(
() => _.debounce(fetchProducts, 500),
[fetchProducts]
);
// The following queries will execute in parallel
const categoryQuery = useQuery({ queryKey: ['category'], queryFn: fetchCategory, keepPreviousData: true });
const productsQuery = useQuery({ queryKey: ['products', category_id, sortPrice, minPrice, maxPrice, page, categoryFilters], queryFn: debouncedFetchProducts, keepPreviousData: true, staleTime: 1000 });
当我运行它时,我收到一条错误消息“查询函数必须返回定义的值”。我相信这是因为 debounced 函数返回一个承诺,但 useQuery 需要一个实际值。
我也尝试过使用useAsync,但我想使用useQuery,因为它有内置缓存。
有人可以帮我弄清楚如何在 React Query 中使用 useQuery 实现 debounce 吗?
提前感谢您的帮助!
您可以利用 useDebounce 钩子在 React-query 中触发
queryKey
更新,而不是使用 Underscore 库中的 debounce
函数。
例如:
const [searchParams, setSearchParams] = useDebounce([category_id, sortPrice, minPrice, maxPrice, page, categoryFilters], 1000)
const productsQuery = useQuery({ queryKey: ['products', ...searchParams], queryFn: fetchProducts, keepPreviousData: true, staleTime: 1000 });
useDebounce
应用于searchParams数组,其中包括category_id、sortPrice、minPrice、maxPrice、page和categoryFilters等变量。
去抖延迟设置为 1000 毫秒(1 秒)。然后,productsQuery 在其查询键中使用去抖搜索参数,确保仅当去抖搜索参数更改时才调用
fetchProducts
函数。
您可以在这个
codesandbox 示例中找到一个有效的
useDebounce
示例
@提拉米苏!以下博客文章解释了如何为 useQuery 编写一个小包装器,以提供消除请求的可能性。这非常简单:https://rafaelcamargo.com/blog/deboucing-requests-with-react-query/