1

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?

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.