How to use object spread with nested properties?

Viewed 40709

I'm trying to return the following in my reducer (react-redux) and it's giving me a syntax error:

return { ...state, loginForm.email: action.payload.email }

state = { loginForm: { email: '', password: '' } } so on

I have babel preset stage 0 installed and es2015. This works fine:

return { ..state, loginForm: action.payload }
3 Answers

Error you are getting because of the this key:

loginForm.email

It's not a valid object key.

Write it like this:

return { 
    ...state, 
    loginForm: {
        ...state.loginForm,
        email: action.payload.email
    } 
}

In JS, a key value of an object is either a String value or a Symbol value. official docs

I think you want something like this:

{ ...state, loginForm: { email: action.payload.email } }
Related