DEV Community

loading...

Discussion on: Updating react nested state properties

Collapse
sambeard profile image
Sam Beard • Edited

What about the usage of the state argument given in the setState callback?
As is explained in this article in the React docs you should avoid using the rendered state while updating state. Instead, the argument from the setState callback should be used like so:

this.setState(state => {
  ...state
})

However doing this with a nested state using variables that are outside of the scope is impossible:

handleEvent = (event) => {
  this.setState(state => {
    ...state,
    field: event.target.value  // event is undefined
  });
}

Any ideas how to solve this?

EDIT: meanwhile I will be using a flat state structure in order to adhere to the component update cycle. I am only using static fields for my state so far so it isn't too bad i guess.
Grouping fields in my component will now look something like this:

state = {
  field1: "",
  field2: 0,
  field3: ""
}

getFieldGroup = () => {
  let {field1, field2} = this.state;
}