array update setstate react code example
Example 1: Updating an object with setState in React
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper
jasper.name = 'someothername'; // update the name property, assign a new value
return { jasper }; // return new object jasper object
})
//2ND METHOD
this.setState(prevState => ({
jasper: { // object that we want to update
...prevState.jasper, // keep all other key-value pairs
name: 'something' // update the value of specific key
}
}))
Example 2: how to update react state array
const [myArray, setMyArray] = useState([1,2,3])
// to update
setMyArray([...myArray, 4]); // --> myArray = [1,2,3,4]