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>
);
}
CodePudding user response:
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.