Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Pagination and useEffect depencency logic

Basically, i have a function that fetches the filtered datas and that is fetchDataFromMain function.

useEffect(() => {
  setHasMorePage(true);
  setPage(1);
  setFilteredEvents([]);
}, [selectedDate, selectedCategory, selectedProvince]);

useEffect(() => {
  if (page === 4) {
    setHasMorePage(false);
  } else {
    setHasMorePage(true)
  }

  if ((page <= 4 && hasMorePage)) {
    console.log("useeffect worked", page)
    fetchDataFromMain();
  } 
}, [page, selectedDate, selectedCategory, selectedProvince])

i have complete all 4 pages. and every pages has 20 datas. when page increases, the data will also compounds 20*2 in the back-end and sends it to client. But, whenever i increase the page with scrolling down and change a filter, the useEffect work twice, and sends two fetch request to the back-end because the page in the condition i check if page smaller and equals to 4, and also even if i make hasMorePage false, it fetch the request anyways.

My problem is, I don’t want to fetch the data twice, but i can’t find a solution. Does anyone have any idea how can i solve this issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is because hasMorePage has not yet become false even if you’re setting it to false and will become false in the next render cycle.

You can probably move this if condition to another useEffect and see if that helps

if ((page <= 4 && hasMorePage)) {
  console.log("useeffect worked", page)
  fetchDataFromMain();
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading