Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading