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.