Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
onClick function is called for every input change

Im trying to post to a local server using an onclick function, but every time the input field changes here, it calls the function, leading to unecessary function calls, and I can't figure out why it is being called here.

const testPost = () => {
  console.log("Clicked!")
  Axios.post('http://localhost:3001/', {testName: "albumName"})
    .then(() => {
      console.log('successful insert')
    });
};

function App() {

  const [albumName, setAlbumName] = useState('')

  return (
    <div className="App">
        <input type="text" name="albumName" onChange={(e) => {
          setAlbumName(e.target.value)
        }}/>
        <button onClick={testPost()}>Submit</button>
      </header>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Lose the (), So it’s just {testPost}.

If you do testPost() you’re calling/executing testPost every time the component renders. As soon as that line is encountered by the JS interpreter, it runs the function.

With onClick, you only want to pass the reference of the function to be called on click. So just use testPost.

Also with react, every time the state changes within a component, it re-renders the whole component, so that’s why your function is being called every time there is an input change.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda