How to add items to a list of products coming from an React api

Asked

Viewed 37 times

0

I have a system that I need to search for a product in an api by name, every time I click add I need to pick up the return of the api and include this product a list calculating the total value and quantity.

As described below, I started useState with the empty object properties, I need to change the quantity and total each time the user adds a new unit, the api returns me the name and unit price, the quantity of products is inserted before adding to the list.

export default function ProductList(){
    const [product, setProduct] = useState('');

    const [item, setItemList] = 
    useState([
       {
         'produto': '',
         'preco': '',
         'quantidade': 0,
         'total': 0
       }

    ]);


function handleAddProduct(event) {
    event.preventDefault();

    async function getProducts() {
        let response = await api.get(`product/${product}`);
        let { produto, preco } = response.data[0];
        var qte = 1;

        setItemList([{
                'produto': produto,
                'preco': preco,
                'quantidade': qte++,
                'total':  preco * qtde     
        }])
    }

    getProducts(); 
}


return (
     <div className={style.contentLeft}>
             <form action="" onSubmit='' method="get">
              <h2>Produtos</h2> 
                <div className={style.formGroup}>
                    <label htmlFor="">Buscar nome do produto </label>
                    <input type="text" name="product"  onChange={e => setProduct(e.target.value)}  style={{ width: '400px'}} placeholder="Digite aqui o que procura"/>
                </div>

                <div className={style.formGroup}>
                  <label htmlFor="">Quantidade de itens</label>
                  <input type="number" name="itens" min="1" onChange={e => setProductQuantity(e.target.value)}  placeholder="Quantidade de itens"  />
                </div>

                <div className={style.formGroup}>
                   <button type="submit" name="adicionar" onClick={handleAddProduct}>Adicionar</button>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>Produto/Serviço</th>
                            <th>Quantidade</th>
                            <th>Preço unitário</th>
                            <th>Total</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                      <tr>
                         {item.map(itemName => {
                            return (
                             <>
                                <td> Livro </td>
                                <td> 2 </td>
                                <td>R$ 29,90</td>
                                <td>R$ 59,80</td>
                                <td><i class="fas fa-trash"></i></td>
                             </>
                                     
                             )
                         })}

                    </tbody>
                </table>
             </form>
         </div> )

inserir a descrição da imagem aqui

  • setItemList([ ...item, { /* novo item */ ]), that’s it?

  • That would be so, but when adding the same item I need only change the amount and the total, I did so only that each time I add it to the list it generates a new value for the same item.

  • But each product has the total and quantity ? How are you using this in each product ?

  • The api only returns me the product name and price, from there I define how many units I want to add in the list, updating the quantity and subtotal if the product already exists in the list.

No answers

Browser other questions tagged

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