Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable.js update a value multiple key in Map

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?

like image 519
Velidan Avatar asked Jan 16 '17 08:01

Velidan


People also ask

How do you update an immutable map?

You cannot update an immutable map, as the message says. Explicitly use a mutable map, or create an updated copy.

Is map immutable in Javascript?

js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .


1 Answers

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'); 
like image 55
Albert Olivé Avatar answered Oct 23 '22 21:10

Albert Olivé