Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda