Home  >  Q&A  >  body text

Unable to set new page of pagination component in NextUI using setState (ReactJS UI lib)

I have a status and pagination component:

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

This Pagination's onChange event has parameters for the current page when you click on it.

I handle the following function that changes the page:

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

I used 2 console.logs to record data. One records the parameters of onChange, and the other records the page status after using setPage. This is my console, when I click on page 1 and page 2, setPage doesn't seem to work when the parameter e changes following the onChange event, so how do I setPage when e changes?

P粉775788723P粉775788723235 days ago371

reply all(1)I'll reply

  • P粉098979048

    P粉0989790482024-01-30 11:15:38

    Setting the state does not happen immediately, so when you record the page state, the state value has not yet been updated. If you want to log out after the page value changes, you can use the useEffect hook.

    useEffect(() => {
      console.log('page', page);
    }, [page]);

    reply
    0
  • Cancelreply