Reputation: 3
I have a reducer, that first gets a list of books array objects without the book copies count property, and than for each book it get the number of copies
const bookList= (state = [], action) => {
switch (action.type) {
case 'BOOKS_REQUEST_SUCCEEDED':
return Object.assign({}, state, action.payload);
case 'BOOKS_COUNT_REQUEST_SUCCEEDED':
return updateBookCopiesCount(state, action);
default:
return state
}
}
const updateBookCopiesCount = (state, action) => {
const newState = state.map((book) => { // updating only the book copies count
if (book.Id === action.payload.Id) {
return { ...book,
copiesCount: action.payload.copiesCount
};
}
return book;
});
return newState;
}
my question is, what is the right redux approach: should I copy each time the entire array with all the objects for each copiesCount update, or is it ok to copy only the object that was modified with the new property
Thanks in advance
Upvotes: 0
Views: 925
Reputation: 784
Redux only requires that you have to return new value instance if there was any changes in data, ie it enforces immutability. And it doesn't enforce the particular form of your reducer. So, your question effectively isn't about redux approach, but about general javascript task how to perform data transformation in immutable way.
From my opinion your code is absolutely normal for this particular task.
Upvotes: 1
Reputation: 67627
The current updateBookCopiesCount
function is correct. You need to copy each level of nesting that needs to be updated, but only what needs to be updated. So, you need to copy state
(which is being done via state.map()
, and you need to copy just the one object inside of the array that needs to be updated. All other objects should be returned as-is.
See the Structuring Reducers - Immutable Update Patterns section of the Redux docs for more info.
Upvotes: 0