I am aware that if it was an ordinary react component or a custom hook it is supposed to return newly updated data if props change but since there is no specific details in the documentation I wanted to know if this is the main reason why data fetching ( refetchProducts) happens whenever query params change or I’m missing some configuration that could help prevent this issue.
What I’m trying to achieve is load all products initially since the 3 query params are all empty and then refetch only filtered products whenever filter button is clicked (NOT whenever the 3 Search Pararams are changed). RefetchProducts is invoked on button click. I thought enabled = false would do the job, but apparently I’m mistaken. Each time any of the 3 Search params ( classification, vendor, searchText ) is changed the request to fetch products is sent. This is not happening in any of my event handlers, which means the query does it itself. What am i missing and what is the best approach in such situations?
import { useQuery } from "react-query";
import http from "../http";
// have to filter data
const useGetFilteredProductsQuery = (
classification,
vendor,
searchText,
options = {}
) => {
return useQuery({
...options,
queryKey: ["customer/products", classification, vendor, searchText],
queryFn: () => {
const params = new URLSearchParams();
if (classification) params.append("classification", classification);
if (vendor) params.append("vendor", vendor);
if (searchText) params.append("searchText", searchText);
return http.get("/products?" + params.toString(), {
withCredentials: true, // This ensures cookies are sent with requests
xsrfCookieName: "token",
});
},
select: (data) => {
return data.data;
},
});
};
export default useGetFilteredProductsQuery;
// component in which the query is used
const { classification, vendor, searchText } = SearchParams; // Zustand store
const {
data: classifications = [],
error: classificationError,
isLoading: classificationLoading,
} = useGetClassificationQuery();
const {
data: products = [],
error: productsError,
isLoading: productsLoading,
refetch: refetchProducts,
} = useGetFilteredProductsQuery(classification, vendor, searchText, {
enabled: false,
});
const INITIAL_ENTRIES_PER_PAGE = 3;
const { page, setPage, displayEntries, pages } = usePagination(
products,
INITIAL_ENTRIES_PER_PAGE
);
// refetchProducts should work only on page load and button click
useEffect(() => {
refetchProducts();
}, []);
...
I tried removing the params from the key array of the query, I tried checking out whether this happens after initial refetchProducts in the useEffect ( removed the useEffect because I know it invalidates the query so I thought something might be going on with the params that I pass)