XoR
XoR

Reputation: 132

how to push a new item into a deeply nested Record in immutableJS

I'm trying to push a new item into a deeply nested immutable record.

  const i = Immutable.Record({
    nested: new (Immutable.Record({
      someKey: [{id:1,name:'adam'}, {id:2,name:'steve'}],
    })),
  });
  const myMap = new i;
  const myNewMap = myMap.updateIn(['nested', 'someKey'], (fav)=>    fav.push({id:3,name:'dan'}));

  console.log(myNewMap.toJS());

what I expect is to update the nested list with the new value, but the actual output is

  [object Object] {
  nested: [object Object] {
    someKey: 3
    }
  }

so Im doing something wrong, so how would I go about updating the record with the new value ?

here is the jsbin for the example http://jsbin.com/nipolimuyu/edit?html,js,console

Upvotes: 1

Views: 908

Answers (2)

malletjo
malletjo

Reputation: 1786

Be careful here.

Your initial obj should all be an immutableJS obj. You can use fromJS().

In your example, you need to add your array as an ImmutableJS list

const i = Immutable.Record({
    nested: new (Immutable.Record({
    someKey: new Immutable.List([{id:1,name:'adam'}, {id:2,name:'steve'}]),
  })),
});
// The bad way, add a normal JS array to an immutableJS Record/map
const i = Immutable.Record({
    nested: new (Immutable.Record({
    someKey: [{id:1,name:'adam'}, {id:2,name:'steve'}],
  })),
});

So at the end you just need to do like you wanted

const myNewMap = myMap.updateIn(['nested', 'someKey'], fav => fav.push({id:3,name:'dan'}));

So now you can use the immutableJS push() function that return a new immutableJS object.

Upvotes: 0

Tomas Kulich
Tomas Kulich

Reputation: 15638

You're missing return statement in a function you pass to updateIn (note that Array.push does NOT return a resulting array!). It should be:

const myNewMap = myMap.updateIn(
  ['nested', 'someKey'], 
  (fav) => {
    fav.push({id:3,name:'dan'})
    return fav
  })

Upvotes: 2

Related Questions