Search code examples
reactjsnextui

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:

  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]);