Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImmutableJS - update value in a List

I have a Map like this (in ImmutableJS):

{arrayOfValues: [
  {one: {inside: 'first in array'}},
  {one: {inside: 'second in array'}}
]}

And I want to update the value "inside" in the second entry in the "arrayOfValues" array. How can I do it? This is what I have now and it says "Uncaught Error: invalid keyPath"

theMap.update('arrayOfValues',(list)=>{
  return list.setIn([1,'one','inside'],'updated value'); 
})

I also tried directly this and it didn't work:

theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value');

After several hours of looking for the solution, I appreciate any help. Thank you.

like image 448
user3696212 Avatar asked Aug 01 '15 23:08

user3696212


People also ask

What is fromJS in immutable?

Immutable. js offers the fromJS() method to build immutable structures from objects and array. Objects are converted into maps. Arrays are converted into lists. The fromJS() method can also take a reviver function for custom conversions.

What is immutability in JavaScript?

An immutable value is one whose content cannot be changed without creating an entirely new value. In JavaScript, primitive values are immutable — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned another value.


2 Answers

What you are doing is correct (see this JSBin).

const orig = Immutable.fromJS({
  arrayOfValues: [
    { one: { inside: 'first in array' } },
    { one: { inside: 'second in array' } },
  ]
});

const updated = orig.setIn(['arrayOfValues', 1, 'one', 'inside'], 'updated value');

console.log(updated.toJS());

// {
//   arrayOfValues: [
//     { one: { inside: 'first in array' } },
//     { one: { inside: 'second in array' } },
//   ]
// }

When you call orig.setIn(), it doesn't modify orig directly. That's the whole purpose of this Immutable library. It doesn't mutate the existing data but creates a new one from the existing one.

like image 117
Brian Park Avatar answered Nov 10 '22 19:11

Brian Park


Your setIn example works as you should see in this plunkr: http://plnkr.co/edit/1uXTWtKlykeuU6vB3xVO?p=preview

Perhaps you are assuming the value of theMap will be changed as a result of the setIn?

As these structures are immutable, you must capture the modified value in a new variable as var theMap2 = theMap.setIn(['arrayOfValues',1,'one','inside'],'updated value');

like image 36
Brian Kent Avatar answered Nov 10 '22 18:11

Brian Kent