1

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?

1 Answer 1

2

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

  1. You are using the value of id as a key for the id property in form and I assume you want it to be form.id
  2. you are destructuring a string, state.form.id and when you do that the output will be each letter in that string

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Okay so best to go with multiple cases with known keys rather than dynamic. That makes sense. I appreciate the response!!
Unless you are dealing with a lot of properties that you need to assign. In that case we can find a solution that dynamically assigns the properties whilst preserving the integrate of the reducer and doesn't mutate the data.
So I actually ran across this on the redux site which touches on this issue and the pattern that should be used. redux.js.org/recipes/structuring-reducers/… I was close it looks like. The data being passed in is unchanging so I know what will be there I just didn't want to write 25 similar reducer cases haha
Yes, have a good read on that page because it covers all the pitfalls mutating data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.