Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React this.setState With Arrow Function Causes Error In Console

I have a very simple form where I'm storing a users email in the component's state and updating the state with an onChange function. There is a strange thing that is occurring where if my onChange function updates the state with a function I get two errors in the console whenever I'm typing. If I update the state with an object, however, I get no errors. I believe updating with a function is the recommended method so I'm curious to know why I'm getting these errors.

My Component:

import * as React from 'react';
import { FormGroup, Input, Label } from 'reactstrap';

interface IState {
  email: string;
}

class SignUpForm extends React.Component<{}, IState> {
  constructor(props: {}) {
    super(props);

    this.state = {
      email: ''
    };
  }

  public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState(() => ({ email: event.currentTarget.value }))
  };

  // Using this function instead of the one above causes no errors
  // public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   this.setState({ email: event.currentTarget.value })
  // };

  public render() {

    return (
      <div>
        <h1>Sign Up</h1>
        <div className='row' style={{ paddingTop: '20px' }}>
          <div className='col-lg-4 offset-lg-4'>
            <form>
              <FormGroup style={{ textAlign: 'left' }}>
                <Label>Email</Label>
                <Input
                  value={this.state.email}
                  onChange={this.onEmailChange}
                  type='text'
                  placeholder='Email Address'
                />
              </FormGroup>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default SignUpForm;

The error messages I get are:

index.js:2178 Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `currentTarget` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See react-event-pooling for more information.

index.js:2178 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: react-controlled-components
like image 319
Jon Lamb Avatar asked Aug 04 '18 14:08

Jon Lamb


2 Answers

If your state update is derived from what is currently in your state (e.g. incrementing a count variable) you should use the update function version of setState.

If you are just setting a completely new value like you do with an event handler, you don't need to use the update function version. The commented out version in your question is perfectly fine.

If you want to use the update function version you must either use event.persist() so that you can use the event asynchronously, or simply extract the value before you call setState.

public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = event.currentTarget;
  this.setState(() => ({ email: value }))
};
like image 120
Tholle Avatar answered Oct 23 '22 11:10

Tholle


You can't use event or any of its descendant properties once the event handler has terminated. Instead, you have to grab the value, then use the function (or if you prefer, use persist, as Tholle points out):

public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = event.currentTarget;
  this.setState(() => ({ email: value }));
};

That said, since you're not updating state based on state or props, this is one of the few situations where using the non-callback version of setState is fine (details):

public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  this.setState({ email: event.currentTarget.value });
};
like image 4
T.J. Crowder Avatar answered Oct 23 '22 11:10

T.J. Crowder