I want to create Immutable.js Records that have a (more or less) unique key. Something like this:
import { Record } from 'immutable'
var MyRecord = Record({
key: Math.random().toString(),
name: ""
})
Is this possible? I've tried it and all records have the same key. I'm importing MyRecord
like this:
import { MyRecord } from '../model/MyRecord'
and create new records like this
var r = new MyRecord(data)
where data
is a json object.
I could add the key manually after creating the new record of course, but I'd prefer to find a way to automate this.
Thanks for the great question and thanks to @robertklep for leading me to this answer by referring to this: How to construct subclasses of Immutable.Record?
Adapting that answer to work with id
s is slightly different: if there is an id
given in the record, it won't generate one.
That's the only change really.
// https://gist.github.com/jed/982883
// this can be any function that returns a string
function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)}
// this is the implementation you need
class MyRecordWithId extends Immutable.Record({
id: '', // purposely have this empty string
a: 'some a',
b: 'some b'
}) {
constructor(props) {
super(Object.assign({}, props, {id: (props && props.id) || uuid()}))
}
}
// this is a test to see the ID
const myRecord = new MyRecordWithId();
console.log('first record id: ', myRecord.id);
// these are tests to see if we can serialize the record and check if the ID is the same
const json = JSON.stringify(myRecord.toJS());
const js = JSON.parse(json);
const shouldHaveTheSameId = new MyRecordWithId().merge(Immutable.fromJS(js));
console.log('serialized id: ',shouldHaveTheSameId.id);
console.log('are the IDs the same?: ', myRecord.id === shouldHaveTheSameId.id ? 'yes' : 'no');
console.log('different id: ', new MyRecordWithId().id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With