The code below is supposed to increment & decrement the quantity by 1 but instead, it is incrementing and decrementing by 2
switch(action.payload) {
case "INC_QUANTITY": {
let newState = state;
newState[action.payload].quantity += 1;
return [...newState];
}
case "DEC_QUANTITY": {
let newState = state;
newState[action.payload].quantity--;
return [...newState];
}
}
newState is an array of objects and each object has its own quantity key, action.payload is the index of object which quantity key value is supposed to be increased by 1 example of object is
const newState = [
{
category: "Female",
desc: "Slim fit regular blue jeans for women",
id: "DyDlMp_7hi",
name: "Blue Jeans",
price: 25,
quantity: 1,
url: "img_url",
}
]
I am using react context API and useContext to transfer data between components and useReducer to manage the state have a look at the code below and you will have an understanding
const [mensProductState, menDispatch] = useReducer(reducer, [...menProducts]);
const [ladiesProduct, ladiesDispatch] = useReducer(reducer, [...feminineProducts]);
const [newArrivalState, newArrivalDispatch] = useReducer(reducer, [...newArrival]);
const [cartState, cartDispatch] = useReducer(cartReducer, []);
const value = useMemo(
() => ({
cartState,
cartDispatch,
ladiesProduct,
ladiesDispatch,
mensProductState,
menDispatch,
newArrivalState,
newArrivalDispatch,
}),
[cartState, ladiesProduct, mensProductState, newArrivalState]
);
return (
<StoreContext.Provider value={value}>
<BrowserRouter>
<Routes>
<Route index element={<Home />} />
<Route path="/cart" element={<Cart />} />
</Routes>
</BrowserRouter>
</StoreContext.Provider>
Below is the SnapShot of the Application
plus icon is supposed to increment the quantity