Liaoyf Liaoyf - 3 months ago 16
React JSX Question

How can I remove some element in List with Immutable?

I use react + redux with Immutable, and how can I remove some element in List with Immutable?

import Immutable, { List, Map, fromJS } from 'immutable';

let initialState = fromJS({
floor: [
{
floor: '1',
rooms: [
{
room: '101'
},
{
room: '102'
},
{
room: '103'
}
]
}
]
});

export default function list(state = initialState, action) {
switch (action.type) {
//remove some room
case REMOVE_ROOM:
//how can I remove some element in List with Immutable?
default:
return state;
}
};


then, I dispatch a action that remove some room with
dispatch(removeRoom('102'))
, but how can I simply to remove
{room: 102}
with Immutable?

Answer

First, write a function findRoomPath to find room path in your state.

And use deleteIn to remove the value at this path.

var roomPath = findRoomPath(state, 101);
state = state.deleteIn(roomPath);

var state = Immutable.fromJS({
    floor: [
        {
            floor: '1',
            rooms: [
                {
                    room: '101'
                }
            ]
        },
      {
            floor: '2',
            rooms: [
                {
                    room: '104'
                }
            ]
        }
    ]
});

function findRoomPath(state, room) {
  var keyPath = ['floor'];
  state
    .get('floor')
    .find((v, k1) => {
      return v
        .get('rooms')
        .find(function(v, k2) {
          if (+v.get('room') === +room) {
            keyPath.push(k1, 'rooms', k2);
            return true;
          }
        });
    
    });

  return keyPath.length > 1 ?
    keyPath :
    null;
}

function deleteRoom(state, room) {
  var roomPath = findRoomPath(state, room);
  return (roomPath) ?
    state.deleteIn(roomPath) :
    state;
}


console.log(deleteRoom(state, 101).toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>