jmona789
jmona789

Reputation: 2839

React- HTTP request is firing on page load

I'm just starting to use react and I have this login model component with the following:

export default class LoginModal extends Component {

  constructor() {
    super();
    this.render.bind(this);
    this.state = {showModal: false}
  }

  close() {
    this.setState({ showModal: false });
  }

  open() {
    this.setState({ showModal: true });
  }

  login() {
    console.log("Hello. It's Me")
    axios.post('https://crossorigin.me/http://requestb.in/w21igbw2', {
      firstName: 'Fred',
      lastName: 'Flintstone'
    })
    .then(function (response) {
      console.log(response);
      //this.setState({ showModal: false });
    })
    .catch(function (error) {
      console.log(error);
    });
  }

  handleSelect(eventKey) {
    event.preventDefault();
    alert(`selected ${eventKey}`);
  }

In the model itself I have <Button onClick={this.login()} bsStyle="btn btn-black btn-block">Login</Button>, but the login() function fires as soon as the page loads not when the button is clicked. Am I doing this the correct way? Most of this code was written by a co-worker with more react experience than me so I may be putting the login function in the wrong place entirely. If so please let me know where the function should go.

Upvotes: 0

Views: 712

Answers (1)

Pranesh Ravi
Pranesh Ravi

Reputation: 19113

this.login() should be given as this.loginto the onClick() handler

<Button onClick={this.login} bsStyle="btn btn-black btn-block">Login</Button>

Upvotes: 1

Related Questions