Pagination works from the second click

Viewed 70

I have such a problem with pagination: it switches to another page only from the second click. When I click on page 2, it also remains on page 1, and only from the second time it switches to page 2. Also with the rest of the pages. I did pagination component like this:

const Paginator = ({
    total,
    startPage = 1,
    limit = 2,
    totalPages = null,
    onMovePage = null,
  }) => {

  const [hovered, setHovered] = useState(false);

  const handleEnter = () => {
    setHovered(true);
  };
  const handleLeave = () => {
    setHovered(false);
  };

  const style = hovered ? { left: "-230px" } : {};

  const [currentPage, setCurrentPage] = useState(startPage);

  function range(start, stop, step) {
    if(typeof stop=='undefined'){/*one param defined*/stop=start;start=0}
    if(typeof step=='undefined'){step=1}
    if((step>0&&start>=stop)||(step<0&&start<=stop)){return[]}
    let result=[];
    for(let i=start;step>0?i<stop:i>stop;i+=step){result.push(i)}
    return result;
  };

  return (
    <>
      ...
      {range(1, totalPages+1).map(p => (
        <PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage})} } title={p} name={p} />
      ))}
      ...
    </>
}

And using it in softwares component:

const PER_PAGE = 2;

const Softwares = () => {

  const [softwares, setSoftwares] = useState([]);
  const [total, setTotal] = useState(null);
  const [totalPages, setTotalPages] = useState(null);

  const onFetchData = ({ currentPage }) => {
    console.log('currentPage in onFetchData', currentPage)
    fetch(`http://127.0.0.1:8000/api/software/?p=${currentPage}&per_page=${PER_PAGE}`)
      .then(response => response.json())
      .then(data => {
        setSoftwares(data.results);
        setTotal(data.count);
        setTotalPages(data.total_pages);
      })
  }

  useEffect(() => {
    onFetchData({ currentPage: 1 })
  }, []);

  return (
    <>
    ...
    {softwares.map(s => (
      <Article key={s.id} pathname={s.id} title={s.title} image={s.image} pubdate={s.pub_date} icon={s.category.parent.img} categoryID={s.category.id} categoryName={s.category.name} dCount={s.counter} content={s.content} />
    ))}
    <Paginator totalPages={totalPages} total={total} onMovePage={onFetchData} limit={PER_PAGE} />
    ...
    </>
  );
};

So why is it happening?

1 Answers

Change the below

<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage})} } title={p} name={p} />

to

<PagItem key={p} handleClick={ () => {setCurrentPage(p); onMovePage && onMovePage({currentPage:p})} } title={p} name={p} />

Because you're assuming your state currentPage is set by the time you call onMovePage which isn't true. Rely on the p to move to that page instead of state which will be set asynchronously.

Related