-1
I’m adding two new input
s for each product that is returning me from <li>
.
In these new inputs I’m putting a onChange
to take whatever is typed and put in my useState
, but I’m having a hard time because it puts inside this array any changes in my input, whether one key or another. Not to mention that I can have several inputs equal according to the number of products coming back.
My question is, would there be any other way to do this?
I’ve been trying to find solutions and doing this for four days and it’s complicated.
const [quantidadeUsada, SetQuantidadeUsada] = useState([]);
const [numeroLote, setNumeroLote] = useState([]);
const onChangeQtdUsada = (ev) => {
const { value } = ev.target;
SetQuantidadeUsada([...quantidadeUsada, value]);
//console.log(quantidadeUsada);
}
const onChangeNrmLote = (ev) => {
const {value} = ev.target;
setNumeroLote([...numeroLote, value]);
//console.log(numeroLote);
}
return (
<ul className="prods-list">
{prods.map(prod => (
<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/>
//AQUI ESTOU ADICIONANDO OS DOIS INPUTS
<label htmlFor="quantidadeUsada">Quantidade Aplicada</label>
<input name="quantidadeUsada" type="text" onChange={onChangeQtdUsada} placeholder="Em metros" />
<label htmlFor="numeroLote">Número do Lote</label>
<input name="numeroLote" type="text" onChange={onChangeNrmLote} />
</li>
))}
</ul>
);
These inputs will be saved in a BD table along with the returned product:
const id_ProdNfe = prods.map(prod => {
return prod.produtoNfe_id;
});
for (var i = 0; i < id_ProdNfe.length; i++) {
const responseProd = await api.post('/consumidor/produto', {
quantidadeUsada: quantidadeUsada[i],
numeroLote: numeroLote[i],
fk_consumidor_id: consumidor_id,
fk_produtoNfe_id: id_ProdNfe[i]
});
console.log(responseProd);
}
When you put the code of a component here in Stack Overflow, I suggest not separating it into different parts, it makes understanding difficult. When necessary, omit the unrelated code, but do not "mess up" the code.
– Rafael Tavares
The way it is there, every time the onChange event is invoked, it adds a new element to the array, but this you must have noticed. If what you want is to change a specific element of the array
quantidadeUsada
, you should pass toonChangeQtdUsada()
an argument that identifies the Indice you want to change. Two options would be the callback index of theprods.map
or thekey
prop
of the list.– Vander Santos