Hello. I have a question. Here is my product Slice file from the Redux toolkit. While adding a product to the cart, I want to compare if my stock count from DB is smaller than the product quantity from the cart. if so want to give a windows alert that warns the product is out of stock? But I couldn’t figure out the logic.
Code: (Slicefile)
import { createSlice } from \”@reduxjs/toolkit\”;
const initialState = {
cartItems: localStorage.getItem(\’cartItems\’) ? JSON.parse(localStorage.getItem(\’cartItems\’)) : [],
};
const cartSlice = createSlice({
name: \”cart\”,
initialState,
reducers: {
addToCart(state, action) {
const itemIndex = state.cartItems.findIndex(
(item) => item._id === action.payload._id
);
if (itemIndex >= 0) {
state.cartItems[itemIndex].quantity += 1;
} else {
const tempProduct = { …action.payload, quantity: 1 };
state.cartItems.push(tempProduct);
}
localStorage.setItem(\’cartItems\’, JSON.stringify(state.cartItems))
},
increaseCart(state, action) {
const itemIndex = state.cartItems.findIndex(
(item) => item._id === action.payload._id
);
if (state.cartItems[itemIndex].quantity >= 1) {
state.cartItems[itemIndex].quantity += 1;
}
localStorage.setItem(\’cartItems\’, JSON.stringify(state.cartItems))
},
decreaseCart(state, action) {
const itemIndex = state.cartItems.findIndex(
(item) => item._id === action.payload._id
);
if (state.cartItems[itemIndex].quantity > 1) {
state.cartItems[itemIndex].quantity -= 1;
}
localStorage.setItem(\’cartItems\’, JSON.stringify(state.cartItems))
},
removeFromCart(state, action) {
const newCartItems = state.cartItems.filter((cartItem) => cartItem._id !== action.payload._id)
state.cartItems = newCartItems
localStorage.setItem(\’cartItems\’, JSON.stringify(state.cartItems))
},
clearAllCart(state, action) {
state.cartItems = []
localStorage.setItem(\’cartItems\’, JSON.stringify(state.cartItems))
}
},
});
export const { addToCart, decreaseCart, increaseCart, removeFromCart, clearAllCart } = cartSlice.actions;
export default cartSlice.reducer;