Asaf Aviv
Asaf Aviv

Reputation: 11780

Is adding conditions to a reducer is an anti pattern?

I have a cart items in my store and i want to check if the user added the same item with the same color and size.

If so i just want to increase the quantity, if not just add it but it creates kinda akward reducer and i wanted to know if this considered as an anti pattern and if so, what can we do to simplify it

export default (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TO_CART':
      // Check to see if we already have the same product
      // with the same color and size in our cart
      const productIndex = state.products
        .findIndex(product => product._id === action.product._id
          && product.size === action.product.size
          && product.color === action.product.color);

      // if we have it already increase the quantity  
      if (productIndex !== -1) {
        const updatedProduct = {
          ...state.products[productIndex],
          quantity: state.products[productIndex].quantity + action.product.quantity,
        };

        return {
          ...state,
          products: [
            ...state.products.slice(0, productIndex),
            updatedProduct,
            ...state.products.slice(productIndex + 1),
          ],
        };
      }

      // if not just save it
      return {
        ...state,
        products: [...state.products, action.product],
      };
    default:
      return state;
  }
};

Upvotes: 0

Views: 110

Answers (1)

markerikson
markerikson

Reputation: 67499

No, it's absolutely not an anti-pattern. Reducers can, and should, do a lot more than just return {...state, ...action.payload}. Now, what logic you put in a reducer is up to you, as well as what abstractions you choose to use in the process.

If you're concerned about writing nested immutable update logic, then I'd suggest looking at the immer immutable update library. I'd also suggest trying out our new redux-starter-kit package, which uses immer internally.

Upvotes: 1

Related Questions