Altair312
Altair312

Reputation: 348

How to stop handleSubmit updating when rendered to another element?

Now trying out some React, and stumbled with a problem that doesn't seem to be covered anywhere.

I have a very simple search form that connects to an API. When an invalid value is returned, it renders a Header 3 element with the error message like:

Invalid value xxx Please enter valid VAT number

The problem in a nutshell, I can't seem to find how to stop "xxx" re-rendering. Before sending a new request, every time I start typing or removing text from the field it was taken from, the "invalid value xxx" gets updated, but I want it to stop

Everywhere I tried looking for any hints or ideas, such cases aren't described anywhere in documentation (or maybe I have no idea where to look). Scouring Internet showed no results as well.

Very simple removal of handleChange and moving this.setState to handleSubmit didn't work, for some odd reason.


     handleChange(event) {
      this.setState({ value: event.target.value });
    }

      <form onSubmit={this.handleSubmit}>
        <label style={Style}>Search VAT:</label>
        <input type="text" style={Style} />
        <input type="submit" value="Submit" />
      </form>
   <h3>
          Invalid value {` `} {this.state.value}
          <br /> <br />
          Please enter valid VAT Number
   </h3>

Upvotes: 0

Views: 39

Answers (1)

Will Jenkins
Will Jenkins

Reputation: 9787

You should separate your invalid value from your state.value.

So if your API call returns an error, at that point copy your current state.value into a new state variable such as state.errorValue. This is what you should use to render your your error message:

<h3>
      Invalid value {this.state.errorValue}
      <br /> <br />
      Please enter valid VAT Number
</h3>

After the user starts typing again or after a successful submsission to the api (whichever suits), clear your state.errorValue.

Upvotes: 2

Related Questions