Reputation: 85
I want to delete a product I click on inside my cart using Redux. I am able to delete a product with "pop" but it obviously deletes the last item on the list instead of the one I click on. Each product has it's own price that I want to subtract from the total as well. The product and it's price have the same index in the products list and shoePrice list.
import {createSlice} from "@reduxjs/toolkit";
const cartSlice = createSlice({
name:"cart",
initialState:{
products: [],
quantity: 0,
total: 0,
shoePrice: [],
},
reducers:{
addProduct:(state, action)=>{
state.quantity += 1;
state.products.push(action.payload);
state.shoePrice.push(action.payload.price);
state.total += action.payload.price;
},
removeProduct:(state, action)=>{
if(state.quantity > 0) {
state.quantity -= 1;
state.total = state.total - state.shoePrice.pop(1);
state.products.pop(1);
}
},
},
});
export const {addProduct, removeProduct} = cartSlice.actions
export default cartSlice.reducer;
Upvotes: 2
Views: 993
Reputation: 99
If you want to remove the product from array using index:
state.products.splice(index, 1)
If you want to just pop the last added product:
state.products.splice(state.products.length-1, 1)
Upvotes: 1