Marina Dunst
Marina Dunst

Reputation: 870

How to use object spread with nested properties?

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 }

Upvotes: 41

Views: 55211

Answers (3)

Phil
Phil

Reputation: 481

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

Upvotes: 0

stevenlacerda
stevenlacerda

Reputation: 1187

I think you want something like this:

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

Upvotes: -6

Mayank Shukla
Mayank Shukla

Reputation: 104379

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
    } 
}

Upvotes: 117

Related Questions