Answer the question
In order to leave comments, you need to log in
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;
}
};
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question