Immutability and updating nested key of local state

redux update state object
redux update array of objects
immutability-helper update object in array
immutable-js
redux update nested object
immer
redux update nested array
redux-immutable

I have the following state.

state = {
  friends: {
    nickNames: ['Polly', 'P', 'Pau'],
    ... here more k:v
    },
  }
}

And I want to update nickNames array with a value coming from an uncontrolled form through a method in my class. However, I'm having issues at the time of determine if I am setting the state properly without mutating it.

I am doing the following

updateArray = (nickName) => {

  const tempDeepCopy = {
    ...this.state,
    friends: {
      ...this.state.friends,
      nickNames: [...this.state.friends.nickNames]
    }
  }

  tempDeepCopy.friends.nickNames.push(nickName)

  this.setState({
    friends: 
    {
      nickNames: tempDeepCopy.friends.nickNames
    }
  })

}

Is this the proper way of doing it? If so, is it also the most efficient given the state? I am trying to avoid helper libraries to learn how to make deep copies.

I will appreciate help since Im trying to learn immutability and it is a concept that is taking me a lot of effort.

setState() in class components does shallow merge.

So you could just ignore other "parent" keys and focus only on friends.

You can also simplify it like:

this.setState({
  friends: { // only focus on friends
    ...this.state.friends, // do not ignore other friend k:v pairs
    nicknames: [
      ...this.state.friends.nicknames,
      nickName
    ]
  }
})

How to update nested state properties in React, In order to setState for a nested object you can follow the below approach as I think setState doesn't handle nested updates. var someProperty = {this.state. However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use immutability-helper package to update the state. See this answer on how to update state with immutability helper.

Why not just;

updateArray = (nickName) => {

  const updatedNickNames = [...this.state.friends.nickNames, nickName];

  this.setState({
    friends: {
      ...this.state.friends,
      nickNames: updatedNickNames
    }
  });

}

Because nickNames is just a array of strings, you can copy it with the spread operator. Also, with setState you can change a specific part of your state, in your case you only have to worry about the friends part.

Immutable Update Patterns, The key to updating nested data is that every level of nesting must be copied and the process of correctly applying immutable updates to deeply nested state  This code can get hard to read when you’re updating deeply-nested items! Redux: Updating an Object by Key (This isn’t specific to Redux – the same method applies with plain React state. See here for how to adapt it.)

You can just use

this.setState({
    friends: 
    {
      nickNames: [...this.state.friends.nickNames, nickName]
    }
  })

State should be only modified through the setState function because if you modify it directly you could break the React component lyfecycle.

Redux immutable update patterns, In this post, we will learn more about Redux, why immutable update is important, and how to handle tricky updates in nested to maintain simple UI or business logic, by all means, use local state In response to application events, these state object params need to be updated, but in an immutable way. The good news is that there is a simple solution: React provides a set of utility functions (called ‘immutability helpers’) that help update more complex and nested models. React Immutability

It is a correct way to do that. The thing is you must never change the state directly. That is it.

I might give a more concise code

state = {
  friends: {
    nickNames: ['Polly', 'P', 'Pau'],
    ... here more k:v
    },
  }
}

updateArray = (nickName) => {
  this.setState(prevState => ({
    ...prevState,
    friends: 
    {
        ...prevState.friends,
        nickNames: [...prevState.friends.nickNames, nickname]    
    }
  }))

}

As long as you do not change the state directly, any way will do through setState()

Handling State in React: Four Immutable Approaches to Consider, This creates a separate copy of the user object that's stored in state. Import at the top: import update from 'immutability-helper'; updateState({target}) { let So if you change the nested object, you'll mutate the original object. #Immutable Update Patterns. The articles listed in Prerequisite Concepts#Immutable Data Management give a number of good examples for how to perform basic update operations immutably, such as updating a field in an object or adding an item to the end of an array.

React, immutable updates and TypeScript : typescript, React, immutable updates and TypeScript lately, and I wonder how others deal with updating nested object state when calling setState . save to local object Object.assign(configData, formattedForConfiguration); } } }) return configData; }. This must be an object! state. thing3 = ['thing3'] // This is regular js, this works without autovivification state. thing3 [1] = 'foo3' // Hmm, notice that state.thing2 is an object, yet this is an array state. thing2. slice // should be undefined state. thing2. slice // should be a function

Immutable.js, Persistent data presents a mutative API which does not update the data in-place, but over time, a value represents the state of that thing at a particular instance of time. If an object is immutable, it can be "copied" simply by making another reference to They also respect the custom toJSON() methods of nested objects. The key design principle here is immutability: using immutable objects and immutable references as much as possible. Let’s review how immutability helps with the main goals of this course: Safe from bugs. Immutable objects aren’t susceptible to bugs caused by aliasing. Immutable references always point to the same object. Easy to understand

Immutability in React and Redux: The Complete Guide, If you looked at some of the immutable state update of a reducer that updates a value nested inside an object,  However, we’ve provided a simple immutability helper, update(), that makes dealing with this type of data much easier, without fundamentally changing how your data is represented. You can also take a look at Facebook’s Immutable-js and the Advanced Performance section for more detail on Immutable-js.

Comments
  • If you use hooks, specifically the setState() hook, you can create multiple state variables, which can make it a lot easier to update the state—you don't always have to merge changes into a single giant state object.
  • prevState is used to monitor the previous state. Since setState is asynchronous, it is a good practice to make sure the previous function is done.