How to set multiple fields at once in Immutable.js Record?
Looking at this, I think that Immutable. Record is the data structure for represent "javascript immutable objects", but I want to update several fields at once without creating several objects calling set each time.
I want to do something like this
class LoginContext extends Immutable.Record(
{ logged : false, loading: false, error: false, user: null}){
}
var loginContext = new LoginContext()
var anotherContext = loginContext.set({'logged':'true', 'error':'false'})
I read that you can't pass an object to Record.set() for API consistency:
Consistency with other uses of set both in this library and in ES6. Map and Set's set can't accept an object, because their keys can be anything, not just strings. Records must have strings, but keeping the API consistent was important.
And I know that I could use:
var anotherContext = loginContext.withMutations(function (record) {
record.set('logged','true').set('error','true');
});
There is another way or I'm misusing Record?
Personally I prefer the merge syntax, it feels more natural:
const newContent = oldContext.merge({
"logged": true,
"error": false
});
If you were doing something very complex, maybe the transient version would be better, but I just can't imagine where.
It also means you can leverage mergeDeep
if needed.
To answer your original question we will use .withMutations()
Here an excerpt from the docs:
Applying a mutation to create a new immutable object results in some overhead, which can add up to a minor performance penalty. If you need to apply a series of mutations locally before returning, Immutable gives you the ability to create a temporary mutable (transient) copy of a collection and apply a batch of mutations in a performant manner by using withMutations. In fact, this is exactly how Immutable applies complex mutations itself.
So you can write something along the lines:
loginContext.withMutations((ctx) => {
ctx.set('logged', true).set('error', false)
});
Besides that I thought that Records could also be used with ordinary js dot notation.
Good luck!
Why don't you just chain multiple sets? Like so:
ImmutableObj.set('key', 'value')
.set('key2', 'value2')
.set('key3', 'value3');
You should do a few things differently. First, don't extend Immutable.Record but use the constructor:
var LoginContext = Immutable.Record({
logged:false,
loading:false,
user: null
}, 'LoginContext');
This returns a class that you can instantiate with an object:
var anotherContext = new LoginContext({logged:true, error:false});