user8490655
user8490655

Reputation: 33

How to get axios.post info after click a button once

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

Answers (2)

csath
csath

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

MattJHoughton
MattJHoughton

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

Related Questions