Stephan
Stephan

Reputation: 375

React default value does not show in input field

I am using Django with React and I am trying to update user profiles, below is what I have tried:

constructor(props){
    super(props);

    this.state = {
        username: '',
        fetched_data: {}
    }

async componentDidMount() {
  const token = localStorage.getItem('token');
  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };
  config.headers["Authorization"] = `Token ${token}`;

  await axios.get(API_URL + 'users/api/user/', config)
    .then(res => {
        this.setState({fetched_data: res.data})
    })
}

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

<form onSubmit={this.onFormSubmit} >

    <div>
        <label>Username:</label>
        <input
            placeholder="Username"
            className="form-control"
            value={this.state.username ? this.state.username : this.state.fetched_data.username}
            onChange={this.onInputChange_username}
        />
   </div>
</form>

I first tried to fetch the user data in componentDidMount() and I stored it in this.state.fetched_data. In the form I tried to set the value to this.state.username if it exist. If it is empty string I then set it to this.state.fetched_data.username.

The problem I am having with the above code is that when I tried to change the field in username, I was not able to erase the value in the input field completely. Each time the field is empty, it reset to the value in this.state.fetched_data.username. I also tried to use the defaultValue like this:

<div>
    <label>Username:</label>
    <input
        placeholder="Username"
        className="form-control"
        defaultValue = {this.state.fetched_data.username}
        value={this.state.username}
        onChange={this.onInputChange_username}
    />

But it also does not work since it only shows the placeholder in the input filed. How do I make this work? Thanks in advance.

Upvotes: 0

Views: 3135

Answers (1)

Matt
Matt

Reputation: 3760

The problem is your conditional assignment of the value of the input field in the render function. When you try to clear the value of the field it just resets to this.state.fetched_data.username so you can never clear it.

Set the initial state when you load the form:

componentDidMount() {
    this.setState({
        username: this.state.fetched_data.username,
    });
}

Then set the value of the input field in render:

<input 
    value={this.state.username}
    onChange={this.onInputChange_username}
/>

And your onChange handler is fine as it is:

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

Upvotes: 1

Related Questions