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

Cannot using setState to set new page of Pagination Component in NextUI (ReactJS UI lib)

I have a state and Pagintion Component:

const [page, setPage] = useState(1);
----------------------------------------------------------------------------------------
<Pagination
  color="primary"
  size="sm"
  total={30}
  onChange={handleChangePage}
  className="mb-20"
/>

The event onChange of this Pagination has the params that is the current page when you click on that page.

My function to handle change page below:

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

  const handleChangePage = (e) => {
    console.log('data',e)
    setPage(e);
    console.log('page', page)
  };

I used 2 console.log to log data. One log params of onChange, one log the page state after using setPage. This is my console when I click page 1 and 2, the setPage seems not working while params e is changing follow onChange event, so How I can setPage when e changing?

enter image description here

enter image description here

>Solution :

Setting state does not happen immediately, so when you are logging the page state, the state value hasn’t updated yet. If you want to log out the page value after it changes, you can use the useEffect hook.

useEffect(() => {
  console.log('page', page);
}, [page]);
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