State is behind

39 Views Asked by At

I have a state pageSize, user will select the pageSize they wish to size their pages. UI

I was able to get my currentPage to update, as well as got my list to fit based on pageSize using useMemo().

  const PAGE_SIZES = [15, 25, 50, 100];

  function BlogList() {

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);

  const updatePage = (pageNum) => {
    setCurrentPage(parseInt(pageNum))
  }; 

  const updateRowsPerPage = (rows) => {
    setPageSize(parseInt(rows));
  };

  const currentPaginationData = useMemo(() => {

    const start = Math.floor( (currentPage*pageSize) - pageSize);
    const end = Math.floor(currentPage*pageSize);

    if(currentPage >= Math.floor(blogs.posts.length/pageSize)) {
      return blogs.posts.slice(start, blogs.posts.length)
    }else{
      return blogs.posts.slice(start, end)
    }

  }, [currentPage]);

Now, I was having trouble with all my states, they were behind, until obviously the page rerendered, but after some research I used useMemo() for currentPagination, worked fine, then updatePage() is working without an issue. In my experience state is always behind when you try setting morew than one state in a function LINE 20. I know its right in front of me, the solution, but I just can't see it, help please!

0

There are 0 best solutions below