Parallel Queries
Để xử lý nhiều query cùng một lúc ở trong React Query, ta có thể dùng hook useQueries.
import { useQueries } from "@tanstack/react-query"Giả sử ta có một query dùng để truy vấn nhiều sản phẩm:
const productsQuery = useQuery({
queryKey: ["products"],
queryFn: async () => {
const res = await axios.get(`${API}/products`)
return res.data
},
})Và ta muốn lấy thông tin chi tiết cho từng sản phẩm. Khi đó, ta có thể dùng hook useQueries như sau:
const productDetailQueries = useQueries({
queries: (productsQuery?.data ?? []).map((product) => ({
queryKey: ["products", product.productId],
queryFn: async () => {
const res = await axios.get(`${API}/products/${product.productId}`)
return res.data
},
})),
})Có thể thấy, thuộc tính queries sẽ nhận vào một mảng các object chứa hai thuộc tính queryKey và queryFn.
Giá trị trả về của useQueries là một mảng các query.
Prefetching
Xét tính năng sau: khi người dùng hover vào một sản phẩm thì ta sẽ lấy thông tin chi tiết về sản phẩm đó mà không cần chờ đến khi người dùng click vào nút xem thêm.
Triển khai tính năng này bằng cách sử dụng phương thức prefetchQuery của query client:
function handleMouseEnter() {
queryClient.prefetchQuery({
queryKey: ["products", productId],
queryFn: async () => {
const res = await axios.get(`${API}/products/${productId}`)
return res.data
},
})
}Có thể thấy, đối số truyền vào prefetchQuery cũng là một object gồm hai thuộc tính queryKey và queryFn tương tự như useQuery.