j_d
j_d

Reputation: 3082

How to affect just one key in a nested object (React)?

So, I have a component setup as such:

export default class Login extends Component {

  state = {
    validatedFields: {
      email: {
        uiState: null,
        message: null,
      },
      password: {
        uiState: null,
        message: null,
      },
    },
  }

  ...etc
}

In a function inside this Login component, I loop through field values and validate them. Inside the loop, if that particular value is invalid, I want to change its uiState to the string 'error'

Eg if just email was wrong, the new state would be:

export default class Login extends Component {

  state = {
    validatedFields: {
      email: {
        uiState: 'error',
        message: null,
      },
      password: {
        uiState: null,
        message: null,
      },
    },
  }

  ...etc
}

What is the easiest way to do this with ES6?

I would like to stay away from things like:

let oldState = this.state
oldState.validatedFields.email.message = 'error'
this.setState(oldState)

This seems very verbose for what is effectively changing the value of one key inside a nested array.

What are alternatives?

Upvotes: 1

Views: 50

Answers (1)

Ashish Chaudhary
Ashish Chaudhary

Reputation: 798

You can do:

this.setState({
    validatedFields: Object.assign({}, this.state.validatedFields,
        email: {
            uiState: 'error',
            message: null,
        })
});

It surely isn't less verbose for a single update but you may wrap this in a function and pass it the field you want to update (like pass in the new email object). This prevents mutation as well as allows you to use email object directly obtained from somewhere else.

Upvotes: 2

Related Questions