Reputation:
import React, {Component} from 'react';
import axios from 'axios';
export default class CreateDog extends Component{
constructor(props){
super(props)
this.state = {
name: '',
activityLevel: '',
description: ''
}
this.newDog = this.newDog.bind(this)
}
newDog(dog) {
var doggy = {
name: this.state.name,
activityLevel: this.state.activityLevel,
description: this.state.descriptione
}
axios.post('/api/createdog', doggy)
.then(response => {
return response.data[0]
})
}
render(){
return(
<div>
<div>
<textarea type="text" placeholder="dog breed name" onChange={(e) => this.setState({name: e.target.value})}> </textarea>
<textarea type="text" placeholder="dog breed activity level" onChange={(e) => this.setState({activityLevel: e.target.value})}> </textarea>
<textarea type="text" placeholder="dog breed description" onChange={(e) => this.setState({description: e.target.value})}></textarea>
</div>
<div>
<button onClick={this.newDog(this.state)}></button>
</div>
</div>
)
}
}
Thank you so much in advance. I'm a beginner, so I recognize that this code my make you cringe. As you can see I have those textareas, which I have programmed to setstate upon change. I also have the button below that is supposed to collect the info on state, and send it to my server, and eventually my database.
Whenever I type anything into the textareas, the console is showing that the axios request is getting fired, but axios is not a part of my onChange function. It appears that my onClick function newDog is getting fired whenever someone types in the textarea and I don't know why.
Any thoughts?
Upvotes: 1
Views: 63
Reputation: 12071
Using parentheses to pass arguments will cause the function to execute immediately:
onClick={ this.newDog(this.state) }
You could make use of an anonymous function in order to pass arguments:
onClick={ () => this.newDog(this.state) }
However, you don’t actually need to pass this.state as an argument so you can just use:
onClick={ this.newDog }
As you are binding newDog in your constructor, you can already access this.state inside newDog.
Upvotes: 0
Reputation: 10350
You have to bind this it as callback : onClick = {() => this.newDog.bind(this)}
Upvotes: 2