Ad

Add Element To List That Is Inside A Map (ImmutableJS)

This is a example of what my state looks like:

  state = {
    messages: [
       {name: 'Bruce', content: 'Hello'},
       {name: 'Clark', content: 'World'}
    ]
  }

I am writing a reducer that will take the ADD_MESSAGE action and add a message to the message list. I would like to take into account the case where the 'messages' key is not defined. I am just starting to use ImmutableJS.

This is how I wrote my function:

 // This is really bad
 const addMessage = (state, message) => {
    let mutableState = state.toJS();
    if(mutableState.messages){
      mutableState.messages.push(message);
    }else{
      mutableState = {messages: [message]}
    }

    return fromJS(mutableState);
 }

I'm pretty sure there is a better way to do that. It should work whether my state argument is Immutable or not. Any idea? Thank you!

Ad

Answer

This is a possible implementation:

const addMessage = (state, message) => 
    state.update('messages', Immutable.List(), 
        msgs => msgs.push(Immutable.Map(message)));

The 2nd arg passed to update is the default value if the key doesn't exist, and the 3rd argument is a closure to take the current value for the key (or default value) and perform the required update. The code also converts the message into an Immutable.Map, but you might prefer to use an Immutable.Record type.

See https://facebook.github.io/immutable-js/docs/#/Map/update for more info on update. updateIn is also very useful for updating store state, as are set, merge, setIn and mergeIn.

Ad
source: stackoverflow.com
Ad