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?
You cannot update an immutable map, as the message says. Explicitly use a mutable map, or create an updated copy.
js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With