0

Trying out immutable-js, I found something that I don't fully understand and want to make sure I'm using set correctly.

Basically, if you use "set()" to set a value of a property with an object or array, it stores a raw object/array, whereas if you use merge, it does what I'd expect, converting the raw array to an immutable list.

So my question is: Should you avoid using set() with objects/arrays for parameter 2?

Jasmine Test example here:

it("can do a thing you shouldn't do(?) - inject a normal object into a Map via set", function(){
    const expected = fromJS({ a:  [ 3, 4, 5 ] });
    const set_value = expected.set("a", [3, 4,5]);
    const merge_value = expected.merge({"a": [3, 4,5]});
    expect(expected.get("a")).toEqualImmutable(set_value.get("a")); // Fails
    expect(expected.get("a")).toEqualImmutable(merge_value.get("a")); // Passes
})

Output is:

Message:               
  Expected             
  List [ 3, 4, 5 ]     
   to equal            
  3,4,5

1 Answer 1

2

You should use set() with objects/arrays only when you want your Immutable objects to contain objects/arrays.

That is to say, this is a style choice without a definitive right answer. A good rule of thumb is to not put mutable object into your immutable collections unless you know what you're doing and you have a really good reason to.

Is it safe?

That depends on what you mean by safe. As of 4.0.0-rc8 getIn, setIn, updateIn, merge, toJS, etc. should all work with Immutable collections containing mutable data, so you're safe in that regard.

On the other hand, if you start putting mutable values in your immutable containers, you lose a lot of the benefits of having an immutable collection in the first place. You no longer have the guarantee that a reference to the same object will always contain the same data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.