H
H
HellYeahOmg2018-10-30 14:18:08
React
HellYeahOmg, 2018-10-30 14:18:08

How to deal with duplicates?

I am writing an online store for practice (no backend, only the stage of adding a cart). I use react and redux.
All uploaded products are contained in store.products.items.
All products added to the cart are contained in store.cart.items.
Basket reducer:

var initialState = {
  items: [],
  totalPrice: 0
};

const addTotalPrice = (oldPrice, newPrice) => oldPrice + newPrice;
const reduceTotalPrice = (oldPrice, priceToDelete) => oldPrice - priceToDelete;

export const cartReducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TO_CART":
      return {
        ...state,
        items: [...state.items, action.payload],
        totalPrice: addTotalPrice(state.totalPrice, action.payload.price)
      };
    case "DELETE_FROM_CART":
      return {
        ...state,
        items: state.items.filter(book => book.id !== action.payload.id),
        totalPrice: reduceTotalPrice(state.totalPrice, action.payload.price)
      };
    default:
      return state;
  }
};

The problem is removing duplicate items.
At the moment, when one of these products is deleted, all similar products are removed from the store, but only 1 item is removed from the ui, similarly with the price (it looks like 1 item is subtracted)
There was an idea with adding a property, for example, count, then stupidly multiplying the price by count and get a normal result, but in React, components are immutable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-10-30
@HellYeahOmg

1. Calculating totalPrice and storing it in a reducer is a bad decision. Changing the amount based on the previous value is an even worse solution. Write a selector that will count totalPrice based on cart.items or count the sum every render.
2. Do not allow duplicate items to be added. Instead, increase the amount.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question