thapatechnical / thapareactecom

535 stars 516 forks source link

getting issue with the reduce() method in cart reducer #16

Closed RealRajnish closed 1 year ago

RealRajnish commented 1 year ago
if (action.type === "CART_ITEM_PRICE_TOTAL") {
        let { total_item, total_price } = state.cart.reduce(
            (accum, curElem) => {
                let { price, amount } = curElem;

                accum.total_item += amount;
                accum.total_price += price * amount;

                return accum;
            },
            {
                total_item: 0,
                total_price: 0,
            }
        );
        return {
            ...state,
            total_item,
            total_price,
        };
    }

getting this error with the reduce() method in cart reducer

cartReducer.js:109 Uncaught TypeError: Cannot read properties of null (reading 'reduce') at cartReducer (cartReducer.js:109:1) at updateReducer (react-dom.development.js:16664:1) at Object.useReducer (react-dom.development.js:17898:1) at useReducer (react.development.js:1626:1) at CartProvider (cartContext.js:24:1) at renderWithHooks (react-dom.development.js:16305:1) at updateFunctionComponent (react-dom.development.js:19588:1) at beginWork (react-dom.development.js:21601:1) at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)

Shakthi-ganesh commented 1 year ago

did that error got fixed? I'm having same problem?

RealRajnish commented 1 year ago

did that error got fixed?

Yes , it has been fixed.

I'm having same problem?

it is causing because , i guess somewhere you have used localstorage . it was causing error due to that code just fix that.

Change your code in cart context

const getLocalCartData = () => {
let localCartData = localStorage.getItem("thapaCart");
const parsedData = JSON.parse(localCartData);
if (!Array.isArray(parsedData)) return [];
return parsedData;
};