eugene
eugene

Reputation: 41665

React, about not mutating state

Suppose I have a state

state = {
  inner1: {
     inner2: {
        foo: var1
     }
  }
}

I want to update foo to var2.

Should I create a copy of state inner1 inner2 so that shallowEqual would see state inner1 inner2 changed?

in code, it would be something like

newState = _.merge({}, state, {
   inner1: {
     innner2: {
        foo: var2
     }
   }
})

(Although I'm not entirely sure how _.merge works, it seems sometimes counter intuitive)

So, conceptually, I'm creating a shallow copy until (nested level) I find the object I want to change.

Or would it be more appropriate to update inner2 only?

var { inner2 } = state.inner1

var newInner2 = _.merge({}, inner2, {
    foo: var2
})

state.inner2 = newInner2

Upvotes: 3

Views: 69

Answers (1)

fubar
fubar

Reputation: 17378

Rather than using Lodash, you could just use the spread operator. This example assumes that there are more properties on inner1 and inner2 than those illustrated in your question. If not, the spreads are entirely obsolete.

this.setState((prevState) => ({
  inner1: {
    ...prevState.inner1,
    inner2: {
       ...prevState.inner2,
       foo: var2,
    },
  },
}));

Upvotes: 2

Related Questions