ohadinho ohadinho - 2 months ago 16
Javascript Question

ImmutableJS - Updating a cell of a matrix

I have this matrix:

const initialState = Immutable.fromJS({
board: [
['','',''],
['','',''],
['','','']
]
});


And this function:

function cellClick(state,i,j) {

const board = state.get('board');
var newBoard = board.map(function(arr) {
return arr.slice();
});
newBoard.set(i,j,'Hi');
alert(newBoard.get(i).get(j));
}



  1. Clones the matrix (to newBoard obj)

  2. Try to set a value for a matrix cell - Doesn't work

  3. Tries to output a message with the cell values - Doesn't work



I've tried to read ImmutableJS docs but couldn't find anything talking about setting a value inside a matrix ("List" type of ImmutableJS).

Answer

You could use .setIn([i, j], 'Hi') but it will not mutate the value. That's the point of ImmutableJS. It will return a slightly changed version of your original data structure. If you just write setIn on a line and don't assign the result anywhere then nothing will happen. Nothing will change. That's the point.

getIn and setIn are very useful. They can also provide default values if something doesn't exist. I also don't think you need .slice() there. You don't need to clone anything at all.

It's an immutable data structure, nobody can change it, that's the beautiful part.

const initialState = Immutable.fromJS({ 
  board: [
          ['','',''],
          ['','',''],
          ['','','']
         ]
});

const nextState = initialState.setIn(['board', 0, 0], 'Hi')

// Now nextState has 'Hi' in it's first column and row.
// initialState is still the same as it was, it is not changed.
Comments