Skip to content
This repository has been archived by the owner on Jul 13, 2024. It is now read-only.

Can not get the latest state varible in onClick callback func, when using react hooks. #411

Closed
nieshangsen opened this issue Sep 7, 2021 · 1 comment
Labels
📦 Archived Open issues when project was archived 🐛 Bug Unexpected behavior to be fixed

Comments

@nieshangsen
Copy link

Describe the bug

Can not get the latest state varible in onClick callback func, when using react hooks.

To Reproduce

function App() {
  const [num, setNum] = useState(0);

  function onClick() {
    console.log("num: ", num);
    setNum(num + 1);
  }

  return (
    <div>
      <Gitgraph>
        {(gitgraph) => {
          const master = gitgraph.branch("master");
          master.commit({
            subject: "Initial commit",
            onClick: onClick
          });
        }}
      </Gitgraph>
    </div>
  );
}

It always print num: 0

Expected behavior

the num variable shoud increase each time the commit dot was clicked.

Screenshots

Context

"react": "^16.8.6",
"react-dom": "^16.8.6",
"@gitgraph/react": "^1.6.0",

Additional information

@nieshangsen nieshangsen added the 🐛 Bug Unexpected behavior to be fixed label Sep 7, 2021
@kanounfoued
Copy link

Hi, I have run into this bug, if you want to get the last variable state of num you can get it this way:

Instead of updating the num this way
function onClick() { setNum(num + 1); }

Try to do this
function onClick() { setNum(prev => prev+ 1); }

This would solve your problem.

I hope this was useful for you.

@nicoespeon nicoespeon added the 📦 Archived Open issues when project was archived label Jul 13, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
📦 Archived Open issues when project was archived 🐛 Bug Unexpected behavior to be fixed
Projects
None yet
Development

No branches or pull requests

3 participants