Omortis
Omortis

Reputation: 1530

erroneous react-controlled-components warning?

This JSX code segment is generating a react-controlled-components warning:

          <input
            type="text"
            className="form-control endpoint-text"
            placeholder="fred.scuttle"
            value={ this.props.internals.username }
            onChange={ this.handleUserNameChange.bind(this) }
          />

Generates this warning in the console:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/docs/forms.html#controlled-components

This is a large react/redux application with many, many controlled components and if you follow the link above, my code looks fine.

Anyone see my error? I can't figure it out. It is possible that the state value 'username' is undefined when this form is loaded, but this is not the warning/error I usually get for calling an undefined state datum.

Thanks in advance!

@Nandu Kalidindi:

  handleUserNameChange = (event) => {
    this.props.emitSetUserName(event.target.value);
  }

which simply sets/updates the username field in the redux state:

export function emitSetUserName(uname) {
  return {
    type: EMIT_SET_NAME_CHANGE,
    payload: uname
  }
}

The initial value for that state variable is loaded from a cookie in the same component:

 componentWillMount = () => {
   let username = cookies.get('uname');
   if ( username !== undefined ) {
     this.props.emitSetUserName(username);
   }
 }

Is this a race condition? I would expect an error for trying to access and undefined state value, not a "controlled input" warning...

Upvotes: 0

Views: 551

Answers (1)

Omortis
Omortis

Reputation: 1530

It was indeed a race condition. I needed to process the cookied and set the state accordingly in the parent component. defaultValue works correctly now, too. Thanks for the feedback!

Upvotes: 3

Related Questions