Reputation: 75
I have a shopping cart application where items can be added or removed. Implemented with Redux Toolkit
The problem is that I have two identical products with the same id added to my cart when you click on the "Add" button and there are two cards with the same product in the cart, and I need to have one card, but their number increased.How can I search for matches by id and, depending on the match, increase the quantity or add a new product to the cart. Tried to implement with forEach but then nothing works
const initialState = {
items: [],
totalQuantity: 0,
};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addItemToCart: (state, action) => {
state.items.forEach((item) => {
if(item.id === action.payload.id) {
state.totalQuantity += 1;
return state.items
} else {
state.items.push(action.payload);
state.totalQuantity += 1;
}
})
},
removeItemFromCart: (state) => {
state.totalQuantity -= 1;
},
},
});
Upvotes: 0
Views: 1432
Reputation: 41
I recently made a proyect related to a cart and I did somethings a little bit different, the initialState has to be an empty array and inside de reduceds we should apply de logic of the cart and quantity variable and the find method with spreed operator to write something like this:
const initialState = [];
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addItemToCart: (state, {payload}) => {
const {id} = payload;
const doesItemExist = state.find((item) => item.id === id);
if(doesItemExist){
return state.map((item) => {
if(item.id === id){
return {
...item,
quantity: item.quantity + 1
}
}
return item;
})
} else {
state.push({
...payload, quantity: 1
})
}
},
The remove reducer takes part of the logic from thew add reducer but decremeting the quantity.
removeItemFromCart: (state, {payload}) => {
return state.map((item) => {
if(item.id === id){
return {
...item,
quantity: item.quantity - 1
}
}
return item;
})
},
},
});
Upvotes: 1