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
}
}
Related videos on Youtube
Author by
Marina Dunst
Updated on November 14, 2020Comments
-
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 over 6 yearsNot sure, this one would override
loginForm
completely and therefore remove thepassword
property. -
khush almost 5 yearsthis will override whole state.loginForm object value
-
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 about 4 yearshow to use in case like that?
-
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 almost 4 yearsyou need to spread the rest of the properties of email if you don't want to be overridden