user3528466
user3528466

Reputation: 196

Edit custom object in react state

I have a Map() object in my app state called myMap. I need to edit a key of this map. So I create a map called newMyMap equels to existing myMap object but with a key-value different.

When I call setState, setting myMap = newMyMap Ract insert new Map (myNewMap) intead delete old Map. How can manager this situation?

Upvotes: 0

Views: 1092

Answers (2)

user3528466
user3528466

Reputation: 196

I found the problem. Have two Map object (or other type) with same value inside is different to have 2 equals object. Maybe I did not keep in mind this.

Upvotes: 0

Hardy
Hardy

Reputation: 5631

I think you just don't understand how react state works.. it's just a object with keys and if you set some other key of course the other key is still there..

So if you want to change the "myMap" just assign new value to it.. like:

const newMyMap = Map({some: 'data'});

this.setState({
  myMap: newMyMap,
});

And you shouldn't modify the existing objects. If you need to just modify some object data, create new object from the old one like:

this.setState({
  myMap: Object.assign({}, myOldObject, {someProp: 'new value'}),
});

Upvotes: 1

Related Questions