Reputation: 1871
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.
Upvotes: 1
Views: 118
Reputation: 2616
I think what you’re looking for is called Record
.
It is a data structure provided the library that has explicit fields and is suited specifically for what you’re trying to do.
On the other hand, Map
objects are just generic containers. You should pick which one you prefer, Record
objects become really useful with Typescript/Flow.
Upvotes: 0
Reputation: 125
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.
Upvotes: 1