Created
November 25, 2015 16:43
-
-
Save kastermester/8c40b35843a38ea7ef5d to your computer and use it in GitHub Desktop.
Immutable.JS deep update examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var state = Immutable.fromJS({ | |
product_preview: { | |
product_type: '', | |
media_items: [ | |
{id: 0, url: 'my_url'}, | |
{id: 1, url: 'my_url'}, | |
{id: 2, url: 'my_url'} | |
], | |
}, | |
}); | |
// TASK: find the item inside the media_items list with id = 1 and update it's url to 'my_new_url' | |
// First, exhaustive solution, using only simple `get` and `set`, and `findIndex` methods | |
var product_preview = state.get('product_preview'); | |
var media_items = product_preview.get('media_items'); | |
var idx = media_items.findIndex(function(item){ | |
return item.get('id') === 1; | |
}); | |
var item = media_items.get(idx); | |
// Now we have the item, update it | |
var newItem = item.set('url', 'my_new_url'); | |
var newMedia_items = media_items.set(idx, newItem); | |
var newProduct_preview = product_preview.set('media_items', newMedia_items); | |
var newState = state.set('product_preview', newProduct_preview); | |
// A bit simpler, by using `getIn` and `setIn` to perform deep get and set operations | |
var media_items = state.getIn(['product_preview', 'media_items']); | |
var idx = list.findIndex(function(val){ return val.get('id') === 1; }); | |
var newState = state.setIn(['product_preview', 'media_items', idx, 'url'], 'my_new_url'); | |
// Lastly, using `updateIn` | |
var newState = state.updateIn(['product_preview', 'media_items'], function(list){ | |
var idx = list.findIndex(function(item){ | |
return item.get('id') === 1; | |
}); | |
return list.setIn([idx, 'url'], 'my_new_url'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment