Reputation: 681
I'm working on a redux Architecture, trying to use Immutable.js.
Here's my mystery... given this state:
var state = Immutable.fromJS([
{"id":0, "url":"http://someUrl", "thumb_url":"http://someUrl", "other_url":"http://someUrl"},
{"id":3, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":1, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":5, "url":"http://someUrl", "thumb_url":"http://someUrl", "yet_another_url":"http://someUrl"}
])
...I want to update a url
. I've tried updating the url
of the third index
like this:
var index = 2;
var new_item = { id: 1, url: 'my_new_url' };
var state = state.setIn([index], new_item);
My problem is that I need to update only the url
(or other properties like thumb_url
), leaving all unchanged properties untouched. I have a new_item
of which I want to insert the relevant updated parts into the given index. How do I do that without recursing over every individual property of the old item and without losing the existing properties?
When I say "update", I mean creating a new state
with the old value(s) changed to the new one(s) as it is common to do with Immutable.js.
Thanks!
Upvotes: 0
Views: 165
Reputation: 9813
setIn will set a new value, which will overwrite your previous value, you may want a mergeIn to merge the new attr to origin value.
var state = Immutable.fromJS([
{"id":0, "url":"http://someUrl", "thumb_url":"http://someUrl", "other_url":"http://someUrl"},
{"id":3, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":1, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":5, "url":"http://someUrl", "thumb_url":"http://someUrl", "yet_another_url":"http://someUrl"}
])
var index = 2;
var new_item = { id: 1, url: 'my_new_url' };
var state = state.mergeIn([index], new_item);
console.log(state.toJS())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script>
Upvotes: 3