Tir*_*isu 11 lodash reactjs axios react-query
我正在使用 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 });
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到一条错误消息“查询函数必须返回定义的值”。我相信这是因为 debounced 函数返回一个承诺,但 useQuery 需要一个实际值。
我也尝试过使用 useAsync,但我想使用 useQuery 因为它具有内置缓存。
有人可以帮我弄清楚如何在 React Query 中使用 useQuery 实现 debounce 吗?
预先感谢您的帮助!
小智 26
您可以利用useDebounce挂钩来触发queryKeyreact-query 中的更新,而不是使用debounceUnderscore 库中的函数。
例如:
const [searchParams, setSearchParams] = useDebounce([category_id, sortPrice, minPrice, maxPrice, page, categoryFilters], 1000)
const productsQuery = useQuery({ queryKey: ['products', ...searchParams], queryFn: fetchProducts, keepPreviousData: true, staleTime: 1000 });
Run Code Online (Sandbox Code Playgroud)
useDebounce应用于 searchParams 数组,其中包括类别id、sortPrice、minPrice、maxPrice、page 和categoryFilters 等变量。
去抖延迟设置为 1000 毫秒(1 秒)。然后,productsQuery 在其查询键中使用去抖搜索参数,确保fetchProducts仅在去抖搜索参数更改时调用该函数。
您可以在这个codesandbox示例中找到一个工作useDebounce示例
| 归档时间: |
|
| 查看次数: |
21319 次 |
| 最近记录: |