mateeyow mateeyow - 3 months ago 20
React JSX Question

Is adding a value inside an array.map considered mutating?

I know redux is strict with state management, but is adding a value from an array of objects considered a no no in redux? Example:



// Consider this array of objects on action
action.arr = [ { test: 'me', hail: 'hydra'}, { test: 'you', ring: 'of fire'} ]
// reducer.js
fn = (state = defaultState, action) => {
...
case action.LORD_COMMANDER:
return action.arr.map(v => {
v.john = 'snow'
return v
})
...
}





Is this completely safe on my reducer or should I use
Object.assign()
?

Answer

I think better use Object.assign. Let's consider two examples

const arr  = [ { test: 'me', hail: 'hydra'}, { test: 'you', ring: 'of fire'} ];
const arr1 = arr.map(v => {
  v.john = 'snow'
  return v;
});

console.log(arr, arr1);

As you can see each Object in two arrays have property john because we change Objects which have same reference that is not safe for previous Array., in example below you can see that only in second Array Objects have property john it is because we make copy of Object

const arr  = [ { test: 'me', hail: 'hydra'}, { test: 'you', ring: 'of fire'} ];
const arr1 = arr.map(v => {
  return Object.assign({}, v, { john: 'show' })
});

console.log(arr, arr1);