Reputation: 4045
I have the following Immutable state initially in my reducer:
const firstState = Map({ "1": {title: "Hello 1", content: "Content 1"}, "2" : {title: "Hello 2", content: "Content 2"} });
Now, in my reducer, when a EDIT_POST action comes in I would like to change some of these fields, if they were changed by the user. So say the user edited the title field (of post no. 1) only. Then I would like to have a new state with the title field changed, but the content field intact.
However, I don't know how to do this.
I have tried a few things, e.g. these two things (at separate times):
case 'EDIT_POST': {
var obj = state.get(action.id);
//let newState = state.setIn(['1','title'], 'New Title');
//let newState = state.set("1", {title: "New Title"});
return newState;
}
The first thing does not work at all, the second thing does away with all other values.
Upvotes: 1
Views: 2350
Reputation: 5317
setIn
isn't working becuase you're mixing plain Javascript objects and immutable.js objects. immutable.js assumes that the entire object is composed of immutable.js objects.
Your map:
const firstState = Map({ "1": {title: "Hello 1", content: "Content 1"}, "2" : {title: "Hello 2", content: "Content 2"} });
should look more like this:
const firstState = Map({
"1": Map({ title: "Hello 1", content: "Content 1" }),
"2": Map({ title: "Hello 2", content: "Content 2" })
});
The nested objects have to be instance of Map or another immutable type, then setIn
will work.
If you have a plain JS object and want to convert it to an immutable object you can use Immutable.fromJS(someObject)
Upvotes: 3
Reputation: 2220
You need setIn()
method. Try this.
case 'EDIT_POST': {
var obj = state.get(action.id);
let newState = state.setIn(['1','title'], 'New Title');
return newState;
}
Upvotes: 0