Updating the array object in React state using immutability helper

23,650

Solution 1

One way to do it would be using $set

let index = 0;
let newState = update(this.state, {
   a: {
     b: {
      [index]: {
               c: { $set: "new value"}
       }
    }
  }
});
this.setState(newState);

jsfiddle

Solution 2

Im importing update from immutability helper here :)

this.state = {
  a: {
    b: [{ c: '', d: ''}, ...]
  }
} 


this.setState((prevState, props) => update(prevState, {
    a: {
        b: {
            $apply: b => b.map((item, ii) => {
                if(ii !== n) return item;
                return {
                    ...item,
                    c: 'new value'
                }
            })
        }
    }
}))
Share:
23,650

Related videos on Youtube

vijayst
Author by

vijayst

Blogs at vijayt.com. Primarily works in React and React Native. Now, working in React, Python, C++

Updated on June 16, 2020

Comments

  • vijayst
    vijayst almost 4 years

    I am updating an object within an array in React state using immutability helper.

    The object I want to modify is nested:

    this.state = {
      a: {
        b: [{ c: '', d: ''}, ...]
      }
    } 
    

    I want to update the prop c within the nth element of b using immutability helper.

    The equivalent code without the immutability helper is:

    const newState = Object.assign({}, this.state);
    newState.a = Object.assign({}, newState.a);
    newState.a.b = newState.a.b.slice();
    newState.a.b[n] = Object.assign({}, newState.a.b[n]);
    newState.a.b[n].c = 'new value';
    this.setState({ newState });
    

    I know the above code is a bit ugly. I am assuming the code using immutability helper will solve my problem. Thanks

    • Niyoko
      Niyoko over 7 years
      Consider using ImmutableJS.
  • Vraj Solanki
    Vraj Solanki about 7 years
    Does update return a new object/element like abc = Object.assign({}, xyz) or it changes the object given as parameter in place??
  • Wish
    Wish over 6 years
    @VrajSolanki For this example, it will return new state object, with new a object (rest keys are the same, old references), with new b array in it, all of the element refernces wont be changed but [index] one. And with new reference for c, the rest will be old references.
  • a15n
    a15n almost 6 years
    @VrajSolanki the $set command will "replace the target entirely". The $merge command will merge the keys of object with the target. github.com/kolodny/immutability-helper#available-commands
  • Onat Korucu
    Onat Korucu about 4 years
    Don't forget to import "update" from immutability-helper. import update from 'immutability-helper';