Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

how to use Immutable.js with ES6 classes?

The below code:

class A {constructor(v) {
    this.v = v;
}}
const a = fromJS(new A({a: 42, someOtherSubTree: {}}));
const aMod = a.updateIn(['v', 'a'], x=>43);

… fails with:

TypeError: a.updateIn is not a function

The simpler set also fails with:

TypeError: a.set is not a function

I've found this related question which is however tagged with 'typescript' so I am not sure how the "wrapping" approach suggested there would translate to pure ES6.

Upvotes: 0

Views: 710

Answers (1)

michelgotta
michelgotta

Reputation: 1001

After const a = fromJS(new A({a: 42, someOtherSubTree: {}})); the typeof a is still an object and to Map like expected. It returns the original object.

This part from the Immutable code shows why. Because your object A is not a "plain object" (see function) nor an array, it's just returned as is.

function fromJSDefault(json) {
    if (Array.isArray(json)) {
      return IndexedSeq(json).map(fromJSDefault).toList();
    }
    if (isPlainObj(json)) {
      return KeyedSeq(json).map(fromJSDefault).toMap();
    }
    return json;
}
// […]
function isPlainObj(value) {
    return value && (value.constructor === Object || value.constructor === undefined);
}

Upvotes: 1

Related Questions