-1
I am building a menu screen, currently I have an array of items and prices that the user selects. I’m showing them on the screen normally. But I need to capture the price of each item, and in the end I need to add up all the prices to reach the total value. I cannot apply the reduce in the correct way, when I do this, it shows me the 0 position (which is the item) and the 1 position concatenated. How can I use reduce? In the hall file I have:
const Hall= () => {
const [breakfast, setBreakfast] = useState([]);
const [order, setOrder] = useState([]);
const OptionMenu = () => {
firebase
.firestore()
.collection('menu')
.doc('breakfast')
.get()
.then((snapshot) => {
setBreakfast(Object.entries(snapshot.data()))
});
}
return (
<div>
<Button onClick={(e) => OptionMenu(e.target.value)} children='Café da manhã'/>
</div>
<div>
{breakfast.map((el, index) => <MenuButton onClick={()=>setOrder([...order,el[0],el[1]])} el={el} key={index}/>)}
</div>
<div>
<p>Total:R${order.reduce((acc, cur)=> acc + cur, 0)}</p>
</div>
);
}
The Menubutton component:
const MenuButton = ({el, index, onClick}) => {
return (
<button onClick={onClick} key={index}>
<p key={el[0]+index}>{el[0]}</p>
<p key={el[1]+index}>R${el[1]},00</p>
</button>
);
}
Photo of how the items and prices are stored in the firebase and concatenation on the page:
You wouldn’t be missing a . Value in your reduce?
<p>Total:R${order.reduce((acc, cur)=> acc.Valor + cur.Valor, 0)}</p>
– Pablo Tondolo de Vargas
Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.
– Bacco