event.target[matches] error on form submit in Meteor React project

I am struggling with this bug. Here's my code:

It's long, so here's a short version: I have a form to create an event, I want handleSubmit() to handle error messages and if there are none, add event to db. I do import {Events}, in fact the form worked before I made some changes. When I run it, I get an error message: Uncaught TypeError: event.target[matches] is not a function. Thanks for anyone looking into this.

export default class Create extends React.Component {
constructor(props) {
  super(props);
  this.state = {
      error: {}
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
  evt.preventDefault();

  this.setState({error: {}});
  let title = this.refs.title.value;
  if (!title) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.title = 'Title has to be filled up.';
      return newState;
    })
  }
  let description = this.refs.description.value;
  if (!description) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.description = 'Description has to be filled up.';
      return newState;
    })
  }


  if (!this.state.error) {
      Events.insert({title: title, description: description});
      this.props.history.push('/home');
  }

and:

     <form onSubmit={this.handleSubmit} noValidate>

        <input ref="title" type="text" name="title" placeholder="Title"
        style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.title}</div>

        <input ref="description" type="text" name="description" placeholder="Description"
        style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.description}</div>

        <button type="submit" className="btn btn-success">Create new event</button>
    </form>

Answers:

Answer

So there are two problems with the code:

  1. setState is async. It resolves after the function executes. Workaround: let error = false at the beginning and then set error = true together with setState call.

  2. Empty objects are truthy. Thanks to error variable, we can just change the condition to if(!error). Or do if(error) {return} - this also works.

Oh, and the error message was from a chrome extension. Sucks that chrome doesn't tell you that an error message came from an extension - at least I don't think it does.

Best,

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.