0

I am trying to learn how to use Immutable.js properly. I found this article: http://frontendinsights.com/immutablejs-with-redux-his-best-friend/.

It has a following code snippet:

const initialState = Immutable.Map({ counter: 0 });
const reducer = (state, action) => {
switch (action.type) {
  case 'INCREMENT':
    return state.set('counter', state.get('counter') + 1);
  case 'DECREMENT':
    return state.set('counter', state.get('counter') - 1);
  default:
    return state;
  }
};

const store = createStore(reducer, initialState);

What confuses me is that for me it looks like the switch is returning Map as a state.

I tried the immutable with following:

var obj = {
  lol: 'trol',
}

var immu = Immutable.Map(obj)
var immu2 = immu
immu2 = immu2.set('lol', 'trollz')
console.log(immu2) // Map {size: 1, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}
console.log(immu2.toObject()) // Object {lol: "tral"}

I thought that Redux states needs to always be objects.

So, what is Map() actually returning and why is it possible to set that as a Redux state?

Jaakko Karhu
  • 2,298
  • 4
  • 28
  • 41
  • I don't believe Redux actually impose any limitation on the type of the state. – Nikolaj Dam Larsen Jan 04 '17 at 13:42
  • @NikolajDamLarsen As stated here, as long as the state is serialisable there is no limitations: http://redux.js.org/docs/Glossary.html#state. However, functions can't be stored to state. And the Map has methods, right? – Jaakko Karhu Jan 04 '17 at 13:51
  • redux is not going to check and make sure there are no methods, it's just going to serialize whatever it can if you ask it to. I use `redux-immutable` to make sure everything works as expected. – Sergiu Paraschiv Jan 04 '17 at 16:46

1 Answers1

0

It is possible, however some of the default middleware in RTK claims it to be 'non-serializable'... More here: Getting an error "A non-serializable value was detected in the state" when using redux toolkit - but NOT with normal redux

ydrea
  • 71
  • 1
  • 1
  • 8