Search code examples
javascriptimmutable.js

Immutablejs - map not making nested objects immutable


I am setting up a map like so:

import { Map } from 'immutable';

const initialState = {
   a: "test",
   b: {
    inside: "inside value"
   }
} 

const otherState = {
   c: "other value"
}

 const myState = new Map({ app: new Map(initialState).merge(otherState) });

This seemed to be working, however when I try to change values inside the nested object it does not seem to be working for me (I'm getting "invalid keypath"). So trying:

myState.setIn(['app', 'b', 'inside'], 'newValue'); 

is giving me an "invalid keypath" error. It's looking like When I log it out that the nested object is not being turned immutable. Unsure what I am doing incorrectly.

Edit - here is a codepen to show the problem - https://codepen.io/ajmajma/pen/rRQoZp


Solution

  • Apparently the correct path should be ['app', 'b', 'inside'] given that app is the only property of the myState object.

    You also need to Immutable.fromJS() your initialState and otherState objects, otherwise nested keys are treated as JS objects, not immutablejs maps.

    const myState = new Map({ app: new Map(Immutable.fromJS(initialState)).merge(Immutable.fromJS(otherState)) });