4

I am trying to create a form which has two inputs and a button. When you click the button, the input fields are used to update the state and then show an alert with the information saved in the state. Currently, I have the inputs changing the state but its calling the alert function every time a letter is added to the input...

handleSubmit= (e) =>{
    alert(JSON.stringify(this.state, null, '  '));
  }

  render() {
    return (
      <div className="App">

            <label>
              Username:
              <input
              type="text"
              name="username"
              placeholder="username"
              value={this.state.username}
              onChange={e => this.setState({ username: e.target.value })}
            />
            </label>
            <label>
              Password:
              <input
              type="text"
              name="password"
              placeholder="password"
              value={this.state.password}
              onChange={e => this.setState({ password: e.target.value })}
            />
            </label>

            <button onClick={this.handleSubmit()}>Submit</button>
            <p>{this.state.token}</p>
          <WelcomeStory></WelcomeStory>
      </div>
    );
  };

Thank you, this is my first front end framework so it has been a big learning curve.

5
  • 9
    Remove parentheses from this.handleSubmit() so it's not called right away. Commented Mar 10, 2019 at 22:53
  • 1
    this will fix your issue : <button onClick={this.handleSubmit}>Submit</button> or <button onClick={ () => this.handleSubmit()}>Submit</button> Commented Mar 10, 2019 at 22:56
  • @ymaghzaz if you do the second option, you'll want to make sure to pass the event object along Commented Mar 10, 2019 at 23:00
  • @azium yeah you are right , but i thinks that the event object will not be needed for this context. Commented Mar 10, 2019 at 23:05
  • 1
    @Josef your solution worked! Thank you! Commented Mar 10, 2019 at 23:14

1 Answer 1

3

You do not want the function being called right away, but rather only when the button is clicked. onClick is an event listener waiting for the button to be clicked before calling this.handleSubmit. By having parenthesis, it will call the handleSubmit function as soon as the component is rendered. There are similar questions on SO where people go into it at greater detail if you would like to understand when you should use parenthesis and when you shouldn't: here and here.

<button onClick={this.handleSubmit}>Submit</button>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.