I am using Redux
for React
and I am trying to change a state which contains a Map
but I'm not sure how to do it correctly.
I'm trying to use the update patterns listed here (but they show examples for objects and arrays only):
I got a constant map like this:
const propertiesMap1 = new Map([
["TITLE1",
{
propertyValues: {
myProperty1 : "myVal1",
myProperty2 : "myVal2",
myProperty3 : "myVal3",
},
isOpen: true
}
],
....
There are 2 maps like these in an array: const arr = [map1, map2]
I'm trying to update a value in a specific map like this:
function updateValueInProperties(array, index, category, value)
{
return array.map( (item, index) =>
{
if(index !== action.index)
{
return item;
}
// Otherwise, this is the one we want - return an updated value
return {
...item,
item.get(category): {
}
};
});
}
but the above has pilation errors..
How exactly do I update the map immutably?
I am using Redux
for React
and I am trying to change a state which contains a Map
but I'm not sure how to do it correctly.
I'm trying to use the update patterns listed here (but they show examples for objects and arrays only): https://redux.js/recipes/structuring-reducers/immutable-update-patterns
I got a constant map like this:
const propertiesMap1 = new Map([
["TITLE1",
{
propertyValues: {
myProperty1 : "myVal1",
myProperty2 : "myVal2",
myProperty3 : "myVal3",
},
isOpen: true
}
],
....
There are 2 maps like these in an array: const arr = [map1, map2]
I'm trying to update a value in a specific map like this:
function updateValueInProperties(array, index, category, value)
{
return array.map( (item, index) =>
{
if(index !== action.index)
{
return item;
}
// Otherwise, this is the one we want - return an updated value
return {
...item,
item.get(category): {
}
};
});
}
but the above has pilation errors..
How exactly do I update the map immutably?
Share Improve this question asked Sep 11, 2019 at 6:57 CodeMonkeyCodeMonkey 12.4k38 gold badges128 silver badges248 bronze badges1 Answer
Reset to default 5Short answer:
To create a »updated clone«: new Map(oldMap).set('x', 'y')
or new Map(oldMap).delete('x')
.
TLDR
The constructor of a map takes an iterable and a map is one. So for instance:
const
m1 = new Map().set('x1', 'y1').set('x2', 'y2'),
m2 = new Map([...m1.entries()])
;
m1 === m2 // false;
m2.get('x1') // y1
So, to update a map in such a way that a new map is created you can, you can convert the old map to an array using .entries()
, update this array and turn that back into a map.
//update a value
const updated = new Map([...m1.entries()].map(
([key, val]) => [
key,
key == 'x1' ? `updated ${val}` : val
]
));
or even shorter, Thanks to all the ments of @VLAZ
const clone = new Map(oldMap).set('x', 'y')
SUMMARY
To flat copy
a map you can use new Map(old)
and to create a modified clone, than all those delete()
, set()
or clear()
methods of the new Map can be used. An intermediate array may offer more flexibility for filtering etc, but will e to some performance cost.