Reputation: 167
this is my state of array.
const [arr, setArr] = useState([
{
"id": 1,
"barcode": "8851907264888",
"qty" : 1
},
{
"id": 2,
"barcode": "8857124022072",
"qty": 1
}
]);
if I want to update qty
to 2
in array[0]
, what should I do?
Upvotes: 1
Views: 105
Reputation: 9769
This is how you can update your single object value. Live demo
export default function App() {
const [arr, setArr] = React.useState([
{
"id": 1,
"barcode": "8851907264888",
"qty" : 1
},
{
"id": 2,
"barcode": "8857124022072",
"qty": 1
}
]);
const handleUpdate=()=>{
arr[0].qty=2;
setArr({...arr})
}
return (
<div className="App">
<h3>{JSON.stringify(arr[0])}</h3>
<button onClick={handleUpdate}>Update</button>
</div>
);
}
Upvotes: 1
Reputation: 497
You can copy the arr to a new array and update the qty field and setArr with new array.
let newArr = [...arr]
newArr[0].qty=2;
setArr(newArr);
Upvotes: 4