1

I have a reducer with an initial state that looks something like this:

const initialState = {
  person: {
    details: {
      addresses: {...},
      invoices: {...},
    },
    tasks: {
      option1: [...],
      option2: [...],
      option3: [...]
    }
  }
}

I WAS updating the state within the reducer by doing something like this:

export const exampleReducer = (state = {...initialState}, action ) => {

  case actions.AN_ACTION:
    state.person.tasks.option1 = [new array]
    state.person.tasks.option2 = [another array]
    return state

  default:
    return state
}

But I was brought to attention this link: https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns/ which recommends doing something like this:

function updateVeryNestedField(state, action) {
  return {
    ...state,
    first: {
      ...state.first,
      second: {
        ...state.first.second,
        [action.someId]: {
          ...state.first.second[action.someId],
          fourth: action.someValue
        }
      }
    }
  }
}

Is there a neater way to go about this?

Thank you.

1 Answer 1

3

Yes, your sample code is mutating the existing state. As that docs page shows, you need to make a copy of every level of nested data in order to create a correct immutable update.

That's one of the reasons why we strongly recommend using the Immer library for immutable updates, preferably as part of our new official Redux Toolkit package.

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

1 Comment

Ahh I see. Ill take a look at that now!

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.