Do not insert null data sequence in Loop POST Reactjs

Asked

Viewed 21 times

0

I am inserting a table in Mysql with a Loop, if the user does not type anything in the two fields: "quantityUsada" and "numeroLote" of the same index, I do not want to save in the database, would have some solution for this?

I took a look at the delete() method, but I don’t know if it’s correct, but I tried to implement according to the code.

const id_Prod = prods.map(prod => {
  return prod.produtoNfe_id;
});

for (var i = 0; i < id_Prod.length; i++) {


  if (quantidadeUsada[i] === "" && (numeroLote[i] === undefined || numeroLote[i] === "")) {

    delete(quantidadeUsada[i], numeroLote[i], id_ProdNfe[i], consumidor_id[i]);
  }

  api.post('/consumidor/produto', {
    quantidadeUsada: quantidadeUsada[i],
    numeroLote: numeroLote[i],
    fk_consumidor_id: consumidor_id,
    fk_produtoNfe_id: id_Prod[i]
  }).catch(error => {
    alert("Não foi possível fazer a inserção das Informações, Por favor tente novamente mais tarde. ");
  });
}
<ul className="prods-list">
  {prods.map((prod, index) => (
  <li key={prod.modelo}>
    <label htmlFor="Modelo">Modelo</label>
    <input name="Modelo" type="text" value={prod.Modelo} disabled/>
    <label htmlFor="quantidadeDisponível">Quantidade Disponível</label>
    <input name="quantidadeDisponível" type="text" value={prod.quantidadeComprada} disabled/>

    <div key={index}>
      <label htmlFor={`quantidadeUsada-${index+1}`}>Quantidade Aplicada (Em Metros)</label>
      <input name="quantidadeUsada" type="number" id={`quantidadeUsada-${index+1}`} onChange={(e)=> onChangeQtdUsada(e, index)} step="any" min="0.1" placeholder="Ex: 1.2"/>

      <label htmlFor={`numeroLote-${index+1}`}>Número do Lote</label>
      <input name="numeroLote" type="text" id={`numeroLote-${index+1}`} maxLength="20" onChange={(e)=> onChangeNrmLote(e, index)}/>
    </div>
  </li>
  ))}
</ul>

  • It doesn’t seem ideal for you to make one post for each item within a repeat loop, but speaking about your doubt... Wouldn’t it be better if (valido) { post } instead of if (invalido) { delete } post?

  • Would have some other way to insert elements from a list without a repeat loop?

1 answer

1

I believe that delete accepts only one value at a time:

delete quantidadeUsada[i];
delete numeroLote[i];
delete id_ProdNfe[I];
delete consumidor_id[i];

The rest would work. More like @Rafael Tavares spoke. It was right to send all products together on a request rather than create an Ajax for each individual. This can pass the server if your site grows in the future.

Browser other questions tagged

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