Reputation: 33
Am i Mutating redux state with this function ?
function addDefinition(object, payload) {
var newObject = Object.assign({}, object);
if(!newObject[payload.guid]){
newObject[payload.guid] = [];
}
newObject[payload.guid].push(payload);
return newObject;
}
I want to create structure to hold data related to different part of application.
Upvotes: 0
Views: 56
Reputation: 2957
Yes. See markerikson's answer. Keep in mind you could avoid this with the spread operator.
const INITIAL_STATE = {
guid: []
}
function addDefinition(state = INITIAL_STATE, payload) {
return {...state, guid: [...state.guid, payload]};
}
In addition you could avoid the if statement with initial state.
Upvotes: 0
Reputation: 67539
Yes, that .push()
statement is mutating in the later calls. In the first call, the array is newly created, so it doesn't qualify as a mutation. In a later call, you've created a new object but copied the existing array reference, so .push()
mutates the existing array.
Upvotes: 1