gajus / redux-immutable

redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.
Other
1.88k stars 82 forks source link

initialState rootReducer, serialise/ desialise state maintaining types #34

Closed beckend closed 7 years ago

beckend commented 8 years ago

Let's say I have a reducer with initialState:

myReducer

Immutable.fromJS({
  uniqueTodos: Immutable.Set([ 'one', 'two' ])
});

Then time to save to local store:

const storeSaveObj = store.getState().toJS();
saveToLocalStorage(JSON.stringify(storeSaveObj));

Then to restore it:

import { getStateFromLocalStorage } from './utils'; 
import { immutableRootReducer } from './rootReducer';
import { createStore } from 'redux';

const initialState = Immutable.fromJS(getStateFromLocalStorage());
const store = createStore(immutableRootReducer, initialState);

Then the reducer has been restored, but as a Immutable.List because of Immutable.fromJS:

const uniqueTodos = store.getState().getIn([ 'myReducer', 'uniqueTodos' ]);
Immutable.List.isList(uniqueTodos);
true
Immutable.Set.isSet(uniqueTodos);
false

Is there a good solution to retain the immutable types somehow?

gajus commented 8 years ago

This question has little to do with redux-immutable itself and more with https://github.com/facebook/immutable-js/.

Regardless, it is an interesting issue, one that I did not even realise I have. : )

Quick Google search brought me to https://www.npmjs.com/package/transit-immutable-js

And thats http://blog.cognitect.com/blog/2014/7/22/transit an intro to Transit data interchange format.

This looks like a reasonable solution.

gajus commented 8 years ago

@beckend I would appreciate if you'd share your findings with others. Can you raise a PR?

kandros commented 8 years ago

Same issue when serializing a Immutable.Set on the server and deserialize for hydratation on client, it becomes an Immutable.List.

Ill try the provided packages

gajus commented 8 years ago

@kandros I have suggested a fix. Is it still an issue?

gajus commented 7 years ago

For the record, I have been using transit-immutable-js in production for a while now. There are no downsides to it, other than a relatively large bundle size addition.