Gotcha with Redux-Persist and Immutable

I learned it the hard way. It took me a while to figure out that Redux-persist does not play well with immutable. By default, it does not REHYDRATE Immutable’s properly. Here is how I work around it.

Look at how I re-hydrate invoices which is a immutable Map. I had to convert it back using Map(byMonth).

import { REHYDRATE } from 'redux-persist/constants';
import { Map, Set } from 'immutable';
// {
// invoices; { id1: invoice1, id2: invoice2, id3: invoice3 }
// byMonth: {
// 201710: [id1, id2, id3, ...],
// 201711: [id4, id5, ...],
// 201712: [],
// }
// usent: Set(id1, id2, id3)
// }
const INITIAL_STATE = {
invoices: Map(),
byMonth: Map(),
unsent: Set(),
};
export default function invoiceReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case REHYDRATE: {
console.log('REHYDRATE');
const { invoices, byMonth, unsent } = action.payload.invoice;
return {
...INITIAL_STATE,
invoices: Map(invoices),
byMonth: Map(byMonth),
unsent: Set(unsent),
};
}
case 'INVOICE_SAVE': {
... etc...
}
... other cases ...
}
default:
return state;
}
}

I learned from google that there are libraries that can resolve this too. But since I only I have few immutable objects, I didn’t bother to learn. Hope this can help someone who is in the same situation.

You may also like to check out another story who has a similar issue in a different context. https://corbt.com/posts/2015/12/17/redux-persist-and-immutablejs-records.html