gitgraph.js icon indicating copy to clipboard operation
gitgraph.js copied to clipboard

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

Open nieshangsen opened this issue 3 years ago • 1 comments

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 avatar Sep 07 '21 13:09 nieshangsen

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.

kanounfoued avatar Mar 14 '22 08:03 kanounfoued