Reputation: 399
I have a state object that has a few nested objects. I'd like to update those nested objects in a dynamic way so i'm not copying and pasting the same logic with slight tweeks in different cases. Here's an example of a case in my reducer.
case UPDATE_MESSAGE_FORM:{
const {id, data} = action.payload
const key = id.toLowerCase()
return {
...state,
form: {
...state.form
[key]: {
// this must be incorrect or not possible
...state.form.key,
message: data
}
}
}
}
Currently that works and I get the message to store in the state object, but if I run that again with another key or even in a different case that is supposed to update another field in that nested object it returns the object with just that field. Can you dynamically spread with a nested object?
Upvotes: 1
Views: 1948
Reputation: 91
There is something you are doing wrong there. You are assigning the value and not the key of id to the key inside form: {...}. Given id = "123dfs2" and state.form.id = "abc" your output would look like:
form: {
[123dfs2]: {
0: "a",
1: "b",
2: "c"
}
}
Yes, you can achieve what you asked, but it is a bit more complicated and also dangerous as you are mutating state with no control to what it is going to be dumped into it. This results into unexpected behaviour and errors.
As a practice it is recommended to always know what you expect from a payload and use it specifically in the reducer. Let me know if you want more information.
Upvotes: 2