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.
setData()call is being executed? Add aconsole.log()in that map function. Does it run?let quantity = x.quantidadeAtual + 1;