0

I'm making a simple form that I want to act when enter is pressed, but for some reason it only works on the second enter press, instead of the first

render() for component:

render() {
    return (
        <form onSubmit={this.handleSubmit}>
            <FormGroup controlId="formBasicText">
                <ControlLabel>MyLabel</ControlLabel>
                <FormControl
                    type="text"
                    value={this.state.value}
                    placeholder="Enter something"
                    onChange={this.handleChange}
                />
                <FormControl.Feedback />
            </FormGroup>
        </form>
    );
}

handleSubmit() :

handleSubmit(e) {
    e.preventDefault();
    myMethod({this.state.value});
}

Why is this only working on the second enter press?

Edit: To be clear, this is only a subset of the object code. Trying to run just this is of course going to fail. I just think whatever is going wrong is likely in either the render of the object or the handleSubmit method.

Just in case, here is the constructor:

constructor(props) {
    super(props);
    this.state = {
        value: "",
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}
mstorkson
  • 1,130
  • 1
  • 10
  • 26
  • Look like it fall with error after `myMethod({this.state.value});`. Did you try to debug or check console output? – degr Mar 13 '17 at 14:12
  • This is a cut down version of my code, I only showed the pieces I think likely responsible for the error. The constructor is not here, nor are several ancilalry methods. my method is not defined in what I have presented here so of course if you try to run just this code it will fail. Everything works fine. Console is logging, there are no errors. Its just that it only works on the *second* enter press. – mstorkson Mar 13 '17 at 14:14
  • Can anything outside of component call `event.preventDefault()` on enter keypress? I mean, will it happen, if you will have only your component in application? – degr Mar 13 '17 at 14:49
  • I'm sorry, I don't understand some of your phrasing, but this component is fairly isolated. Nothing should be calling `e.preventDefault()` outside of my `handleSubmit()` method – mstorkson Mar 13 '17 at 14:53
  • Check your app for this constructions: `var stopped = false;window.addEventListener('keypress', function(e){if(!stopped){e.preventDefault();stopped = true}});` – degr Mar 13 '17 at 14:57

1 Answers1

0

Could it be because it queues an update of the state rather than implementing the change immediately like when using this.setState, so the state's new value is not accessible when the function is called?

Have a look here: ReactJS this.setState() out of sync with this.state.myvar

Community
  • 1
  • 1
cal barry
  • 31
  • 1
  • 2