Reputation: 33
When I want to get info from axios.post by clicking a button. But now I wanted to click the button twice to display the info. How should I do?
class ButtonComponent extends React.Component {
state = {display:"ini"};
rep = "ini";
click() {
var self = this;
axios.post("url", {})
.then((rep) => {
self.rep = rep.data;
})
.catch((err) => {
self.rep = err;
})
this.setState({
display: this.rep
});
}
render() {
return (
<div>
<button onClick={this.click.bind(this)}> click me </button>
{this.state.display}
</div>
);
}
};
Upvotes: 3
Views: 12859
Reputation: 1316
This will not display the values you need. Because at the time you are setting up the state inside click method your promise is not resolved.
You can do something like this. Once a user click on button disable button till the axios post is done. Then call setState so that you can see that data inside your div.
class ButtonComponent extends React.Component {
constructor(props){
super(props);
this.state = {
data: '',
isLoading: false,
};
this.click = this.click.bind(this);
}
click() {
this.setState({ isLoading: true });
axios.post("<MY_URL>:3900/find/rapinfo", {})
.then((response) => {
this.setState({ data: response.data, isLoading: false });
})
.catch((err) => {
this.setState({ data: err, isLoading: false });
});
}
render() {
return (
<div>
<button onClick={this.click} disabled={this.state.isLoading}> click me </button>
{this.state.data}
</div>
);
}
}
Upvotes: 5
Reputation: 1118
You've 2 options.
Bind your click event in the constructor:
constructor(){
this.click.bind(this)
}
And then your button becomes
<button onClick={this.click()}> click me </button>
or you can use es6 arrow functions to pass this too it, and declare your click functions like this:
click = () => {
}
and then your button will become:
<button onClick={this.click}> click me </button>
Upvotes: 0