How to use object spread with nested properties?

34,546

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
    } 
}
Share:
34,546

Related videos on Youtube

Marina Dunst
Author by

Marina Dunst

Updated on November 14, 2020

Comments

  • Marina Dunst
    Marina Dunst over 3 years

    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 }
    
  • Philippe Sultan
    Philippe Sultan over 6 years
    Not sure, this one would override loginForm completely and therefore remove the password property.
  • khush
    khush almost 5 years
    this will override whole state.loginForm object value
  • Nux
    Nux about 4 years
    ``` const obj = { one: { a: 'at level one', two: { b: 'at level two', three: { c: 'at level two', z: 'I want to use spread operator to update this' } } } }; ```
  • Nux
    Nux about 4 years
    how to use in case like that?
  • Mayank Shukla
    Mayank Shukla about 4 years
    @Nux, one possible way is to expand till that point, like this: return { ...state, obj: { ...state.obj, one: { ...state.obj.one, two: { ...state.obj.one.two, three: { ...state.obj.one.two.three, z: newValue, } } } } }, another way could be use deep cloning then change that value.
  • Vladyn
    Vladyn almost 4 years
    you need to spread the rest of the properties of email if you don't want to be overridden