0

I tested out produce method from immer library AND tried to use import immer/es5 which did not import. Doing an import immer works fine, but the deep copy fails in that "the initial object is modified" for the following code

const child = new Child("dean", "child")
const initialState = new Person("John", "Doe", 50, "blue", child);

const nextState = produce(initialState, draft => {
  initialState.child.firstName = "Bob"
})

console.log("compare object identity="+ (nextState === initialState))

console.log("next="+JSON.stringify(nextState))
console.log("initial="+JSON.stringify(initialState))

Now, then I use redux-toolkit's createReducer function and this function works fine and DOES a deep copy without modifying the original initial data like so

  const child = new Child("dean", "child")
  const initialState = new Person("John", "Doe", 50, "blue", child);

  const modifyAction = createAction('modify2')

  const counterReducer = createReducer(initialState, (builder) => {
    builder
      .addCase(modifyAction, (state, action) => { state.child.firstName = "Bob" })
  })

  const nextState = counterReducer(initialState, { type: 'modify2' })

  console.log("compare object identity="+ (nextState === initialState))

  console.log("next="+JSON.stringify(nextState))
  console.log("initial="+JSON.stringify(initialState))

I would like to be able to use a produce method that works sometimes 'outside of reducers' in case I need to modify state. I am not sure where to find the correct one. I tried looking at redux-toolkit code but was not sure how to trace into it(that's a whole other question that would be nice to know).

thanks, Dean

Dean Hiller
  • 19,235
  • 25
  • 129
  • 212

1 Answers1

1
const nextState = produce(initialState, draft => {
  initialState.child.firstName = "Bob"
})

You are updating the wrong variable. You need to be updating the draft but instead you are updating the initialState. It should be:

const nextState = produce(initialState, draft => {
  draft.child.firstName = "Bob"
})
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102