Search code examples
javascriptreactjsreduximmutable.jsordered-map

How to add key value pair as last entry in OrderedMap..?


Possible duplicate: Add an Item in OrderedMap with Immutable.js

Working with redux store and Immutable js OrderedMap.

Redux store structure:

   {
     "app": {
        "name": "Test app",
        "dataPack":{
          "chemID": "aaaa",
          "item": {
            "yp57m359": {
            "solid": 33,
            "liquid": 45,
            "gas": 65
           },
           "h58wme1y": {
             "solid": 87,
             "liquid": 9,
             "gas": 30
           },
           "dff56fhh": {
             "solid": 76,
             "liquid": 43,
             "gas": 77
           }
         }
       }
     }
  }

Reducer code:

return state.setIn(["app","dataPack","item",action.item_id],
  fromJS({
    "solid": action.soildVal,
    "liquid": action.liquidVal,
    "gas": action.gasVal
}));

where action.item_id is the random id (key for every item).

Above code works perfectly for adding items.

Problem is: Items stored in a random position. I need to keep the order I am adding. Need to add every item as last entry inside item. Adding one by one item is not in same order.

Help me to get a clear solution for this.


Solution

  • An OrderedMap will remember the order you put things in it. Every time you call .set(key, value) with a new key on an OrderedMap, it will get added to the end.

    let state = Immutable.Map({
      "app": Immutable.Map({
        "name": "Test App",
        "dataPack": Immutable.Map({
          "chemId": "aaaa",
          "items": Immutable.OrderedMap({}) // this is the thing we want ordered
        })
      })
    });
    
    state = state.setIn(['app', 'dataPack', 'items', 'yp57m359'], Immutable.Map({
      'first': 'item'
    }));
    state = state.setIn(['app', 'dataPack', 'items', 'h58wme1y'], Immutable.Map({
      'second': 'item'
    }));
    state = state.setIn(['app', 'dataPack', 'items', 'dff56fhh'], Immutable.Map({
      'third': 'item'
    }));
    
    
    console.log(state.toJS()); // notice things are in order
    <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>

    It's hard to tell exactly where your problem is because we can't see how you created your store, but my guess would be that "item" is pointing to a regular old Map instead of an OrderedMap. If you're just using fromJS(data) to create your state, it will default to using a Map instead of an OrderedMap.