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()?
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);
in this case you are making your state to be the array and since the array in the action is always going to be different then yes you are mutating the state. as long as the objects are not references the state will be completely mutated a sample of a dirty state is.
var objA = {};
var objB = {};
action.array = [objA, objB];
in this case when you do the map your reference to the array would be new but the reference to the objects would be the same. here it would be advised to use Object.assign or (...) operator inside of your map function. or better yet i would recommend looking into immutablejs to handle immutable data
https://facebook.github.io/immutable-js/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With