0

im trying to run this code for cart details and i got an error, yet i couldnt obtain the result due to the error above,the error points directly to the (cartDetail.map )The code looks correct but coulnt figure out where the error is. id like anyone to assist with a fix.

 useEffect(() => {

       let cartItems = [];
       if (props.user.userData && props.user.userData.cart) {
           if (props.user.userData.cart.length > 0) {
               props.user.userData.cart.forEach(item => {
                   cartItems.push(item.id)
               });
               dispatch(getCartItems(cartItems, props.user.userData.cart))
                   .then((response) => {
                       if (response.payload.length > 0) {
                           calculateTotal(response.payload)
                       }
                   })
           }
       }

   }, [props.user.userData])

   const calculateTotal = (cartDetail) => {
       let total = 0;

       cartDetail.map(item => {
           total += parseInt(item.price, 10) * item.quantity
       });

       setTotal(total)
       setShowTotal(true)
   }

Toto
  • 89,455
  • 62
  • 89
  • 125
braspy
  • 45
  • 1
  • 7
  • Use `forEach` instead of `map`. `map` is for getting one array from another by applying a function (which necessarily must return a value) to each element - if you just want to "do something" with each element, as here, `forEach` is the correct tool. – Robin Zigmond Jul 19 '20 at 23:06
  • Thanks. tried it and i didnt get any error – braspy Jul 19 '20 at 23:12
  • @cssyphus happy to do so, but the reason I didn't do that in the first place was that I feel sure this has been asked before - but I confess I was too lazy to look for a duplicate myself – Robin Zigmond Jul 20 '20 at 05:40
  • 1
    Does this answer your question? [JavaScript: Difference between .forEach() and .map()](https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map) – Robin Zigmond Jul 20 '20 at 05:43

0 Answers0