I’m new to react and working on simple eCommerce application. I am changing the quantity of in the cart when it is added more than one times but it gives wrong result(As we can see in the output the ‘quantity’ I print and in the object are different eg. before:1 after:2 but in the object it is 3).I’ll appreciate any help. Thank You!!
here is my reducer.js
export const initialState = {
basket : [],
}
const reducer = (state, action) => {
switch(action.type){
case "ADD_TO_BASKET":
const newIndex = state.basket.findIndex((basketItem)=> basketItem.id==action.item.id)
if(newIndex >= 0){
const newBasket = [...state.basket];
console.log(newBasket);
console.log("quantity "+newBasket[newIndex].quantity);
newBasket[newIndex].quantity+=action.item.quantity;
console.log(newBasket);
console.log("quantity "+newBasket[newIndex].quantity);
return{
...state,
basket: [...newBasket]
}
}
return{
...state,
basket: [...state.basket ,action.item]
}
.
.
.
export default reducer;
here is my checkout.js:
import { useStateValue } from "./StateProvider"
function Checkout() {
const [{basket}, dispatch] = useStateValue();
return (
<div className='checkout'>
<div className="checkout__left">
<img src="https://images-na.ssl-images-amazon.com/images/G/02/UK_CCMP/TM/OCC_Amazon1._CB423492668_.jpg" alt="" className="checkout__ad" />
<div>
<h2 className='checkout__title'>
Your Shopping Basket
</h2>
{basket.map(item => (
// console.log("checkout product quantity: "+JSON.stringify(item.quantity)),
<CheckoutProduct
key={i++}
id = {item.id}
title = {item.title}
image = {item.image}
price = {item.price}
rating = {item.rating}
quantity = {item.quantity}
/>
))}
.
.
.
StateProvider.js:
import React, { createContext, useContext, useReducer } from 'react'
//prepares the data layer
export const StateContext = createContext();
//wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
//pull infromation from the data layer
export const useStateValue = () => useContext(StateContext);
Output in console:
-> [{…}]0: {---, quantity: 3}length: 1[[Prototype]]: Array(0)
-> quantity 1
->[{…}]0: {---, quantity: 3}---
-> quantity 2