0

I have an array of items like so:

initialState = {
shoppingCart: [
        {   
            id: 1,
            name: "Roses",
            title: "Roses",
            text: "Beautiful hand picked roses fresh out of our gardins",
            price: 9.99,
            imageurl: require("../../Images/Flowers/Roses.jpg").default
    },
    {
        id: 2,
        name: "Dahlia",
        title: "Dahlia",
        text: "Beautiful hand picked Dahlia fresh out of our gardins",
        price: 17.99,
        imageurl: require("../../Images/Flowers/Dahlia.jpg").default

    },
  ]
}

And I have a reducer dispatch call:

case "CALCULATE_TOTAL":
    let len = state.shoppingCart.length;
    let total;
    for (let i = 0; i < len; i++) {
        total += state.shoppingCart[i].price
        //console logging total which should return the sum of the shopping cart, returns NaN instead
        console.log(total)
            //when I try to return total I get an error which has nothing to do with total so I'm guessing I'm doing something really wrong
            return total
        }
        return {...state,
            calculatedTotal: total}

When I try to calculate the sum of shoppingCart[index].price through the for loop I get NaN and it throws an error if I try to return the value with a variable. What am I doing wrong?

momomo
  • 299
  • 1
  • 4
  • 14
  • 4
    `let total;` -> `let total = 0;` – VLAZ May 11 '21 at 19:19
  • Relevant: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) and [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – VLAZ May 11 '21 at 19:20

0 Answers0