I am working on a React JS app, where I need to fetch transactions from the backend and display it to the user. Here, I am fetching and displaying transactions with Pagination (50 transactions at once). I have used an useEffect()
hook with pageNo
in the dependency array so that whenever the page changes new transactions get fetched. Here is my code:
useEffect(() => {
setLoading(true);
axios
.get(`${TRANSACTIONS_ENDPOINT}`, {
params: {
page: paginationConfig.pageNo,
search_by: searchConfig.search_by,
search_value: searchConfig.search_value
},
})
.then((response) => {
const { transactions, total_pages, page} = response.data;
setTransactions(transactions);
setPaginationConfig({
...paginationConfig,
pageNo: page,
totalPages: total_pages,
});
setLoading(false);
sessionStorage.setItem(PAGE_STORAGE_KEY, page.toString());
})
.catch((err) => {
console.error(err);
});
}, [paginationConfig.pageNo]);
It is working as expected whenever the user navigates to a different page using page navigation at the bottom of the table. However, in the case when a user rapidly changes the page, it keeps on refreshing with pages fluctuating between different page numbers and keeps on making continuous API requests.
2
Answers
Maybe you should use an abort controller to cancel the previous request if the user rapidly changes pages. Also, you should update the dependency array because once any of these changes, a fetch request is called.
You just need to add a
cleanup
function at the end ofuseEffect
.refs
https://react.dev/reference/react/useEffect