I'm working on one of my first react projects and got this question.
What is the best way to handle and store data in react with using this.state
?
My current workflow:
- fetch data from api in
componentDidMount()
- storing the data in
this.state
(for example inthis.state.account_data
as child object` - using the data in
value
attributes of controls like<input>
in this way:this.state.account_data.username
- each control has his own
onChange
-handleronChange={e => this.onChangeUsername(e)}
The method onChangeUsername(e)
changes this.state
with this.setState({username: e.target.value})
.
So, the problem is: After changing the unsername control value, I have two variants of the username in this.state
: this.state.account_data.username
and this.state.username
. That requires to create another part of code to update this.state.account_data
, because I want to send the new data to the API by UserService.update(this.state.account_data)
.
Is there an easier way or what is the best practice?