0

i want to just add an element to a list somewhere in my immutable object tree.

This question appears to have been answered here :

Append value to List

But for some reason it does not work for me.

If I have the following code :

var myState = {
  a: {
    b: {
      c: [
        {name: 'hi', value: 2},
        {name: 'howdy', value: 3}
      ]
    }
  }
}
myState = Immutable.fromJS(myState);
myState = myState.update(['a', 'b', 'c'], function (myList) {
  myList.push({"name": "hallo", "value": 4})
  }
);

I get an error :

Uncaught TypeError: Cannot read property 'push' of undefined

which indicates that the myList parameter being passed into the callback is null.

Why is this happening?

fiddle:

https://codepen.io/owatkins/pen/brMava

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225

2 Answers2

1

This is how it should be written:

myState.updateIn(['a', 'b', 'c'], function (myList) {
    return myList.push({"name": "hallo", "value": 4})
  }
);

Below is a working example:

var myState = Immutable.fromJS({
  a: {
    b: {
      c: [{
          name: 'hi',
          value: 2
        },
        {
          name: 'howdy',
          value: 3
        }
      ]
    }
  }
})

myState = myState.updateIn(['a', 'b', 'c'], function(myList) {
  return myList.push({
    "name": "hallo",
    "value": 4
  })
});

console.info('myState = ' + myState.toJS())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

notice that I'm using updateIn instead of update and returning the result of push

thedude
  • 9,388
  • 1
  • 29
  • 30
-1

After much stuffing around, the only solution I could come up with is to get the array, and convert to JS, push an element onto it, then convert it back to an immutable... and then use setIn, NOT updateIn, and NOT update.

var myState = {
  a: {
    b: {
      c: [
        {name: 'hi', value: 2},
        {name: 'howdy', value: 3}
      ]
    }
  }
}
myState = Immutable.fromJS(myState);

var list = myState.getIn(['a', 'b', 'c'])
var list = list.toJS();

list.push({"name": "hallo", "value": 4});

var v = Immutable.fromJS(list)

myState = myState.setIn(['a', 'b', 'c'], v)

This looks like a horrible solution, but it is the only thing that works for me so far.

Usually it takes about 5 minutes to learn how to add an element to a list in a framework or language.

I wasn't expecting it to take 5 HOURS.

The documentation for this framework is an absolute disgrace.

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225