Reputation: 23
I need to update a property of an object inside an array with useState . But it don't update the quantity, where is the error?
( It is the initial state, i get all the rest of objects with axios from the server )
const [data, setData] = useState([
{
codigo: 0,
quantidadeAtual: 0,
grptipo: "",
grupo: 0,
identificacao: "",
preco: ""
}]);
function diminuirQuantidade(key: number) {
setData(data.map(x => {
let quantity = x.quantidadeAtual + 1;
if (x.codigo !== key) return x
return {...x, quantidadeAtual: quantity};
}));
}
{data.map((data) => {
// console.log(data.codigo);
if (data.identificacao === "") {
} else {
data.quantidadeAtual = 0;
return (
<div className={estilos.subcontainer} key={data.codigo}>
<div>
<div>
<div>
<h1>{data.identificacao}</h1>
</div>
<div className={estilos.containerBotao}>
<button onClick={() =>
diminuirQuantidade(data.codigo)}>-</button>
<h2>{data.quantidadeAtual}</h2>
<button>+</button>
</div>
</div>
<div>
<h2>{data.preco}</h2>
</div>
</div>
</div>
);
}
})}
My data is like this:
[{
codigo: 308
grupo: 3
identificacao: "Água Mineral Com Gás"
preco: "R$ 3.50"
quantidadeAtual: 0
tipo: "Simples"
}, {...}]
I expected every time I click a button it decreases the quantity of one element. It don't show any error message.
Upvotes: 1
Views: 772
Reputation: 7326
The issue is that you set data.quantidadeAtual
to 0
on render (in data.map((data) => ...)
). This means that after pressing one of the buttons, you increment the quantity and then re-render (since state changed), which triggers the reset to 0. If you remove that line of code (and instead do that in an effect or wherever that logic belongs), it seems to work as expected.
Upvotes: 2