nextui icon indicating copy to clipboard operation
nextui copied to clipboard

[BUG] - Pagination onChange reading state's initial value

Open uki-strzelecki opened this issue 2 years ago • 2 comments

Describe the bug

Reading state value inside Pagination's onChange always results in the initial value.

Your Example Website or App

https://codesandbox.io/s/nextui-custom-pagination-style-forked-p4g40c?file=/pages/index.tsx

Steps to Reproduce the Bug or Issue

See the example in the given link, namely at:

  const [currentPage, setCurrentPage] = useState<number>(1);
  ...
  const onPageChange = (page: number) => {
    console.log("currentPage:", currentPage); // <- this will always be 1
    console.log("onPageChange page:", page);
    setCurrentPage(page);
  };

Expected behavior

currentPage should result in an updated state value.

Screenshots or Videos

No response

Operating System Version

macOS, Sandbox container (probably linux?)

Browser

Chrome

uki-strzelecki avatar Jul 15 '22 07:07 uki-strzelecki

Hi @uki-strzelecki It seems not to be a NextUI bug. onPageChange as a callback would "remember" the initial value of currentPage no matter how many times the page updates because it's accessing currentPage in its closure.

cyanxiao avatar Jul 19 '22 14:07 cyanxiao

Hi @imchell. I am not too familiar with how things work in the background, but how will the same callback passed to e.g. onPress of a standard element have the updated value? In my short experience with React, this is the behavior I am familiar with and what I would expect, that is why it seemed strange to me with Pagination it is not so. Thanks!

uki-strzelecki avatar Jul 19 '22 16:07 uki-strzelecki