-1

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:

  1. fetch data from api in componentDidMount()
  2. storing the data in this.state (for example in this.state.account_data as child object`
  3. using the data in value attributes of controls like <input> in this way: this.state.account_data.username
  4. each control has his own onChange-handler onChange={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?

  • Avoid state manipulation directly. User React-Redux instead. Refer [here](https://www.valentinog.com/blog/redux/) for an introduction. – Debargha Roy Oct 20 '20 at 09:51
  • Why should I avoid state manipulation directly? –  Oct 20 '20 at 09:57
  • It becomes tough as the application grows in size. And why not try redux? I'm sure you won't ask that question once the concept hits you. It's far more logical and easier to maintain a single source of truth for the entire application. – Debargha Roy Oct 20 '20 at 10:05
  • `redux` is good when you have different components sharing the same state and you would like to avoid the necessity of a parent component storing it and passing down the data via `props`, HOC pattern. In a lot of case it may result in overingeering, or unuseful if you go with another state management architecture, for example `Apollo` + `Next` + `Graphql`. – Nja Oct 20 '20 at 10:17

1 Answers1

1

According to official documentation, React suggests to use this library to handle data mutations: immutability-helper.

The idea is that in your onChangeUsername(e) you will copy the original part of state you need to update with update function. In this case const myNewAccountData = update( this.state.account_data, ... ) and then you set the new state with this.setState({account_data : myNewAccountData }).

See this answer for an example on updating nested object with immutability-helper.

And Here you can find an explanation on why to avoid nested object as React state or at least why it may be considered not a best practice.

Nja
  • 439
  • 6
  • 17