vaibhav deep
vaibhav deep

Reputation: 845

How to find the total price from a list of items in React?

I am working on an eCommerce website to React. When a user adds a product in his cart, the state of the cart gets updated. It looks like this -

const[cart, setCart] = useState([]);

everything works fine, the cart is updated with the help of Firestore. Each item in the cart has properties - id, image, productName, and productPrice

I want to display the total price (sum of prices of all the items in the cart). What I try to do is this -

const getCartTotal = () => {
    let total = 0;
    {
      cart?.map((item) => total + item.productPrice);
    }
  };

But this gives me an error in the browser -

Line 37:7: Expected an assignment or function call and instead saw an expression no-unused-expressions

What should the correct approach be? Thanks in advance!

Upvotes: 0

Views: 1448

Answers (1)

keshav
keshav

Reputation: 135

I would suggest you to use reduce instead of map there.

My solution has both map and reduce for your clarity. You were making some small mistake within map function. You were just returning the total + item.productPrice but you were not storing it anywhere.

const cart = [
  {
    price: 23,
    id:1
  },
  {
    price: 27,
    id:2
  },
  {
    price: 60,
    id:2
  },
  {
    price: 40,
    id:4
  }
]
function findSumUsingReduce(){

  const s = cart.reduce((s,{price}) => s+price,0)
  return s;
}

function findSumUsingMap(){

  let t = 0;
  cart.map(({price}) => t = t + price)
  return t;
}

const totalUsingReduce = findSumUsingReduce()
const totalUsingMap = findSumUsingMap()

console.log('totalUsingReduce',totalUsingReduce)
console.log('totalUsingMap',totalUsingMap)

Upvotes: 1

Related Questions