Reputation: 2423
This question might have been asked before but I couldnt find answer after sufficiently searching for one.
I am working on a React app and I need to store the state which is a map in a local variable.
Following is my code which takes the component state and stores it in blockMap:
let blockMap = this.state.editorState.getCurrentContent().getBlockMap();
Then I declare a new Map:
let tempMap = new Map();
Now, I need to store values into the tempMap. So I do something like this:
blockMap.forEach((k,v) => tempMap.set(k,v));
And then I just print out the tempMap to see the set variables. Unfortunately, I get an empty map again. I just dont understand why this is happening. Can someone explain to me if its an ES6 issue or something else?
Following is the full function:
printMapOfEditorState(){
let blockMap = this.state.editorState.getCurrentContent().getBlockMap();
let map = this.state.map;
let tempMap = new Map();
blockMap.forEach((k,v) => tempMap.set(k,v));
console.log(tempMap);
}
Just one more follow up, in the same function I change the map state by using setState like this:
blockMap.forEach(k => {
if(k.getText().replace(/^\s+|\s+$/g, '') !== undefined) {
this.setState({
map: map.set(k.getText(), k.getDepth())
});
}
});
And surprisingly this works. I cant understand this anomolous behaviour. Thanks for help.
Upvotes: 1
Views: 57
Reputation: 32392
The arguments to the callback to forEach
take the form of (value, key)
as opposed to (key, value)
, so your forEach
should look like
blockMap.forEach((v,k) => tempMap.set(k,v));
^^^ swapped
But you actually don't need a forEach since Map
can take another map in the constructor:
let tempMap = new Map(blockMap);
Upvotes: 1