javascriptreactjsimmutable.js

ImmutableJs with Object


Is it possible to use immutablejs like this:

Modal

class PeriodModel {
    constructor(
        id,
        title,
    ) {
        this.id = id;
        this.title = title;
    }
}

export default PeriodModel;

ImmutableJs

let immutable = Map(new PeriodModel(1, 'title!'));

Or is it not immutable anymore? Normally I would do it like this:

let immutable = Map({ id: 1, title: 'title!'});

Please let me know if this is good practice.


Solution

  • I can't say if it's good practice or not, but your way of doing it doesn't seem to work; it doesn't make an Immutable Map, it just makes a PeriodModel.

    I added a method to your class, toObject that returns a plain object of the class's properties.

    class PeriodModel {
        constructor(
            id,
            title,
        ) {
            this.id = id;
            this.title = title;
        }
    
        toObject() {
            return {
            id: this.id,
            title: this.title
          }
        }
    }
    
    const periodMap = Immutable.fromJS(new PeriodModel(1, 'title!').toObject());
    const periodMapWithoutMethod = Immutable.fromJS(new PeriodModel(1, 'title!'));
    

    periodMap will be an Immutable Map but periodMapWithoutMethod will be a plain object.