0

let say I have state in redux

const initialState = {
 age: 0,
 title: undefined,
 body: undefined,
 author: undefined
}

I want to update it with the newState that I get from my backend and it has exactly the same key (age, title, body, author) so in order to make it immutable, I use spread operator

const updateState = (state, newState) => {
 return {...state, ...newState}
}

The problem is that this function works well but what if the body is a object and has nested object in it. I want to make a function that I can reused. I dont want to update it manually key by key

I came across Immer and still cannot figure out how to make a function updateState (not update key by key manually). Could you please show me how to do it?

coinhndp
  • 2,281
  • 9
  • 33
  • 64
  • Can you share a bit more about what you want to achieve, probably using an example object and expected result? A code sandbox with current progress will be highly appreciated. – Dani Vijay May 14 '19 at 12:00

1 Answers1

5
const updateState = produce((draft, action) => {
 Object.assign(draft, action);
})

or

const updateState = produce((draft, action) => {
 return {...draft, ...action}
})

In either case the idea with immer is to either return a new state or mutate the draft object directly, but never both.

CashLion
  • 51
  • 1
  • 3
  • 1
    Welcome to Stack Overflow. It would be helpful if you could explain why your code would solve the problem. – Adrian Mole Dec 14 '19 at 15:14
  • Had this problem today! The explanation is that you need to mutate the draft object with `Object.assign`, that way Immer will understand that the object was changed. – Johan Lindskogen Sep 17 '20 at 11:53