How to take position 1 of the array and add?

Asked

Viewed 124 times

-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:

itens no firebase página do hall

  • You wouldn’t be missing a . Value in your reduce? <p>Total:R${order.reduce((acc, cur)=> acc.Valor + cur.Valor, 0)}</p>

  • 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.

1 answer

1


On this line (which I will call line A.1),

{breakfast.map((el, index) => <MenuButton onClick={()=>setOrder([...order,el[0],el[1]])} el={el} key={index}/>)}

you are separating the product name from its value; at the end of the operation, the content of order shall be (line A.2):

['Café americano', 5]

When it comes time to calculate the total with reduce, you will have a string and a number inside order, so you should probably be getting NaN or a string concatenated with the initial 0 of acc:

<p>Total:R${order.reduce((acc, cur)=> acc + cur, 0)}</p>  

See below the code with some fixes and adaptations for Stack Overflow:

const {useState} = React;

function MenuButton(props) {
  return (
    <button onClick={props.onClick} key={props.key}>
      <p key={props.el[0]+props.key}>{props.el[0]}</p>
      <p key={props.el[1]+props.key}>R${props.el[1]},00</p>
    </button>
  );
}

function Hall() {
  const [order, setOrder] = useState([]);

  const breakfast = [
    ['Café americano',5]
  , ['Café com leite',7]
  , ['Misto quente', 10]
  , ['Suco natural', 7]
  ];

  return (
    <div>
      <div>
        {breakfast.map((el, index) => <MenuButton 
          onClick={() => setOrder(order.concat({titulo:el[0], preco:el[1]}))}
          el={el}
          key={index}
        />)}
      </div>
      <div>
        Total: R$ {order.reduce((acc,x) => acc + x.preco, 0)}
      </div>
    </div>
  );
}

ReactDOM.render(<Hall />, document.getElementById('content'));
<div id="content"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.