简体   繁体   中英

How to convert a plain JS object to an Immutable collection?

I have parts of a state managed with the help of Immutable collections. For example,

const FolderModel = Record({
    id: null,
    name: '',
    items: List()
})

const DocsModel = Record({
    folder1: new FolderModel({
        id: 1,
        name: 'Избранное'
    }),
    folder2: new FolderModel({
        id: 2,
        name: 'Отложенное'
    }),
    folder3: new FolderModel({
        id: 3,
        name: 'Топ тендеры'
    })
})

const initialState = new DocsModel()

I also save my state in a localStorage , so the problem is when retrieve the state from localStorage I don't know how to convert JS object back to a nested collection (eg Record containing a field that is a List). I already tried using Immutable.fromJS() method but apparently it doesn't work for Record s. Did anybody face the same problem? Please help resolving it

I believe you need to serialize your collection with JSON.stringify() before setting it to localStorage. After getting it back from localStorage you can deserialize it with JSON.parse()

I've had success using the transit-immutable-js lib.

From the docs :

"Transit is a serialisation format which builds on top of JSON to provide a richer set of types. It is extensible, which makes it a good choice for easily providing serialisation and deserialisation capabilities for Immutable's types."

Example usage with Records:

var FooRecord = Immutable.Record({ a: 1, b: 2, }, 'Foo'),
    foo = new FooRecord(),
    serialize = transit.withRecords([FooRecord]),
    json = serialize.toJSON(foo);

console.log(json); //=> json string of your data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM