I’m utilizing RTK Query for managing API requests in my React application, particularly for pagination. In my component, I have implemented pagination using useGetPopularItemsQuery from RTK Query. However, I’m encountering a problem with automatic request triggering when certain parameters change.
Here’s a simplified version of my component:
const PopularItemsListing = ({ limitedSet, categoriesSet }: Props) => {
const [currentPage, setCurrentPage] = useState(1);
const [tryAgain, setTryAgain] = useState<boolean>(false);
const [noMoreItems, setNoMoreItems] = useState<boolean>(false);
const { ref, inView } = useInView();
const [allPopularItems, setAllPopularItems] = useState<ItemType[]>([]);
const [shouldSkip, setShouldSkip] = useState<boolean>(false);
const { data, error, isLoading } = useGetPopularItemsQuery(
{
page: currentPage,
limit: 8,
limited: limitedSet,
tags: categoriesSet.join(","),
},
{ retry: tryAgain, skip: shouldSkip }
);
// Other rendering logic and event handlers...
};
The issue arises when either categoriesSet
or limitedSet
changes, I have to reset the page to 1 and this triggering multiple requests due to RTK Query’s behavior (due to changing the other variables and the page counter). I want to ensure that if either of these parameters changes, the pagination resets to page 1 before making a new request.
But if the user is just scrolling and only the page number is changing, I want to make a request with the updated page number.
How can I achieve this behavior effectively with RTK Query?
Hoping to find some help.