I am trying to get total price of items added and removed in Cart, but total just increase and no decrease when remove one item.
I’m working with reducer and I am almost sure that I’ve implemented here the logic but I’m very stuck in this trouble.
This is my code reducer in CartRedux.js
const cartSlice = createSlice({
name: "cart",
initialState: {
products: [],
quantity: 0,
total: 0,
},
reducers: {
addProduct: (state, action) => {
state.quantity += 1;
state.products.push((product) => product._id === action.payload);
state.total += action.payload.price * action.payload.quantity;
},
clearCart: (state) => {
state.products = [];
},
deleteProductStart: (state) => {
state.isFetching = true;
state.error = false;
},
deleteProductSuccess: (state, action) => {
state.isFetching = false;
state.quantity -= 1;
state.products.splice(
state.products.findIndex((item) => item._id === action.payload),
1
);
//agregar aquí la función para restar el total en el RESUMEN DE COMPRA
},
deleteProductFailure: (state) => {
state.isFetching = false;
state.error = true;
},
}
});
3
Answers
You can use the array filter method to remove a specific element from an array without mutating the original state.
Alternatively you can use slice to remove elements from your state:
Also you are not decreasing your total value when you delete one item from your state.
All in all your deleteProductSuccess function should look like:
The
deleteProductSuccess
case reducer isn’t computing/recomputing a total, but instead is only adjusting the total quantity.Both
quantity
andtotal
are what would be considered derived "state", meaning these are easily computed values from actual state, and don’t generally belong as part of the state as it’s considered a React anti-pattern. The suggestion here is to instead store just theproducts
array and compute the derived state thecart.products
array.Example:
Getting the cart quantity & cart total in component
I am sharing the code , as I did the same for mini project
store.js
I hope it will help you