John Doe John Doe - 3 months ago 8
React JSX Question

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?

Answer

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.

Comments