Reputation: 6029
I am trying to use Immutable.js. So I used the Map object and I have a 2 fields for ex.
const initialState = Map({
isUserAuthorized : false,
pending : false
});
and I want to update both. How I can do that? I tried to use a standard Update method like that:
state.update( "isUserAuthorized", () => true, "pending", () => false);
But it isn't working somehow. So I have only one idea - update only particular key and after that do the same with other and return a result.
But I think it is a not so perfect idea. Maybe other normal variants exist? Thanks for any help!
P.S. I found that it can be done via set and withMutations like:
initialState.withMutations(map => {
map.set("isUserAuthorized", true).set("pending", false);
})
But is it really so hard to update multiple values in Map?
Upvotes: 6
Views: 3418
Reputation: 898
Bit of a stale post but in case this helps anyone else, I just had to figure this out yesterday. Here is what I ended up doing.
If you want to change all the keys to be the same then you can map.
const initialState = Map({
isUserAuthorized : false,
pending : false
});
const newState = initialState.map(() => true)
// { isUserAuthorized: true, pending: true }
If there's specific keys you want to set then add a condition or ternary expression in your map and only update what's relevant. Here's a quick and dirty example.
const initialState = Map({
isUserAuthorized : false,
pending : false,
dontChangeMe: false
});
const newState = initialState.map((val, key) => (
key === 'isUserAuthorized' || key === 'pending' ? true : value
)
// { isUserAuthorized: true, pending: true, dontChangeMe: false }
If you want to get clever and make things reusable you could make a curried utility to pass in a list of the target keys, then just invoke with the value you want them to be.
Upvotes: 0
Reputation: 4209
You can use .set():
const initialState = Map({
isUserAuthorized : false,
pending : false
});
initialState = initialState.set('isUserAuthorized', true);
initialState = initialState.set('pending', false);
If you don't want to repeat it. You can create a function to pass multiple params.
Another way is with .merge():
const newState = initialState.merge({
isUserAuthorized: true,
pending: false
});
Or chaining multiple sets:
initialState = initialState.set('isUserAuthorized', true)
.set('pending', false)
.set('key3', 'value3');
Upvotes: 7