0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.