Reactjs - setState does not work with the first value in onClick

Asked

Viewed 168 times

0

Bom di!

I’m using React in version 16.11.0 and every time I use setState using function, the first value I Seto, it always comes blank.

Follow the example below:

  //Declaração do State
  const [senha, setSenha] = useState('');

  //Criação do componente botão
  export default function Button({ children, ...rest }) {
    return (
      <Botao type="button" {...rest}>
        {children}
      </Botao>
    );
  }


  //Chamada do Componente botão e com função onClick
  <Botao
  value={BotoesPassword[0]}
  onClick={event => {
    setSenha(event.target.value);
    console.log(senha);
  }}
  >

Print as it appears on the console( The first line is on 1 Click and the second on 2 Click)

inserir a descrição da imagem aqui

Thank you for your attention

1 answer

0

This is because updates of component state values do not happen immediately after the setState run - value only changes at next time render. You can check this using an Effect like:

React.useEffect(() => {
  console.log(senha);
}, [senha])

This Effect will be executed once, when its component has finished mounting, and once subsequently each time senha change.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.