I have a React app with a profile outlet route, where the index is the 'products'. I also have a similar route called 'savedProducts'. The difference is that the 'products' page lists by outletparam (uid), and the savedProducts uses session uid.
For the API calls I have a service layer with the following functions:
export const listProducts = async (
signal: AbortSignal,
axiosPrivate: AxiosInstance,
uid: User["id"],
size: number,
page: number
) => {
const response: ApiResponse = await axiosPrivate.get(
API.PRODUCT.LIST_PRODUCTS(uid, size, page),
{ signal }
);
const data = response.data.message;
if (data.next) {
data.next = page + 1;
}
return data;
};
export const listSavedProducts = async (
signal: AbortSignal,
axiosPrivate: AxiosInstance,
size: number,
page: number
) => {
const response: ApiResponse = await axiosPrivate.get(
API.PRODUCT.LIST_SAVED_PRODUCTS(size, page),
{ signal }
);
const data = response.data.message;
if (data.next) {
data.next = page + 1;
}
return data;
};
These are essentially the same. I also have custom hooks that use these service functions respectively:
const MAX_PRODUCTS_PER_PAGE = 20;
export const useListProducts = (
dependencies: any[] = [],
params: {
uid: User["id"] | null;
}
) => {
const axiosPrivate = useAxiosPrivate();
return useInfiniteQuery<any, ApiError>({
queryKey: [QUERY_KEY.listProducts, ...dependencies],
queryFn: ({ signal, pageParam }) =>
listProducts(
signal,
axiosPrivate,
params.uid,
MAX_PRODUCTS_PER_PAGE,
pageParam as number
),
enabled: !!params.uid,
initialPageParam: 1,
getNextPageParam: (lastPage) => lastPage.next ?? undefined,
});
};
export const useListSavedProducts = (dependencies: any[] = []) => {
const axiosPrivate = useAxiosPrivate();
return useInfiniteQuery<any, ApiError>({
queryKey: [QUERY_KEY.listSavedProducts, ...dependencies],
queryFn: ({ signal, pageParam }) =>
listSavedProducts(
signal,
axiosPrivate,
MAX_PRODUCTS_PER_PAGE,
pageParam as number
),
initialPageParam: 1,
getNextPageParam: (lastPage) => lastPage.next ?? undefined,
});
};
Here's how I use them in a component:
const [pages, setPages] = useState<Inventory[] | null>(null);
const { data, isLoading, isFetchingNextPage, isError, fetchNextPage } =
useListProducts([user.id], {
uid: user.id,
});
// const { data, isLoading, isFetchingNextPage, isError, fetchNextPage } = useListSavedProducts();
useEffect(() => {
if (data?.pages) {
setPages(data.pages);
}
}, [data]);
The issue is that when I navigate between the pages the API calls will not happen. See network tab
Why is that? Maybe im using dependencies or query keys wrong? How can I fix
useListProducts
anduseListSavedProducts
used entirely separately in their own distinct routes, or loaded together (perhaps in some parent) at the same time?<Route path='/profile/:uname' element={ <ProfileProvider>{withSuspense(Profile)</ProfileProvider>}> <Route index element={<Products />} /> <Route path='products' element={<Products />} /> <Route path='saved' element={<SavedProducts />} /> </Route>