javascriptreactjsreact-reduximmutable.js

How to add a new key/value pair in a nested Map using Immutable.js


I want to add a new key/value pair to a Map which is nested in another Map. If the key already exists it should get replaced.

I thought mergeDeepIn() should to the trick but I get an "invalid keyPath" Error.

The state looks like this:

{
   "requests":{
      "1":{
         "title":"I have a question",
         "customerId":2,
         "messages":{
            "222":{
               "text":"Hello!",
               "senderId":1,
            },
         },
        ...
      },
      ...
   },
}

'requests' and 'messages' are immutable Maps.

I tried this:

const message = fromJS({
  "5": {
    text: "test",
  },
})
state.mergeDeepIn(['requests', 1, 'messages'], message)

The message should get added to the 'messages' Map.


Solution

  • Immutability is a property of a data structure and means: After that data structure is created it will never ever change again. Adding or replacing a value from/to a Map means mutating the Map, which is exactly what immutable-js tries to prevent.

    What you can do is create a new Map from your already existing one.

    const {Map} = require('immutable');
    m = Map({a:1});
    
    Map({...m.toJSON(), b:2}) // Map { "a": 1, "b": 2 }
    Map({...m.toJSON(), a:2}) // Map { "a": 2 }
    m.set('a', 2) // Map { "a": 2 } , creates a new map same as line above