Reputation: 17
I am new to react. I have got an issue updating a quantity.
const[persons,setPersons] = useState(personLists)
if you console.log(persons) it will give output as below. Now I want to update qty for particular misc index of particular person index . I have two persons in below array and each person have further two misc array
[
{
id: 1,
name: "john",
gender: "m",
misc: [
{
id: 1,
name: "xxx",
qty: 1
},
{
id: 2,
name: "xxx1",
qty: 1
}
]
},
{
id: 2,
name: "mary",
gender: "f",
misc: [
{
id: 1,
name: "aaa",
qty: 1
},
{
id: 2,
name: "bbb",
qty: 1
}
]
},
]
Now i want to update qty under misc array for that particular person.I have a function that takes the index of person array and index of misc array as below.
const updatePersonMiscQty = (personIndex, miscIndex) => {
setPersons(persons =>
persons.map((person,key) => {
const found = person.misc.find(d => key === miscIndex);
if (found) {
found.qty += 1;
}
return person;
})
}
let say my personIndex is 0 and miscIndex= is 1 so when usse click the button It should look into first person array, go to second index of misc and update qty.
I am looking for a solutions
Upvotes: 1
Views: 53
Reputation: 41447
access the items by indexes and update
setPersons(persons => {
const miscItem = persons[personIndex]?.misc?.[miscIndex]
if (miscItem ) {
miscItem.qty += 1;
}
return [...persons];
}
})
Upvotes: 1