1this.setState(prevState => {
2 let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper
3 jasper.name = 'someothername'; // update the name property, assign a new value
4 return { jasper }; // return new object jasper object
5})
6
7//2ND METHOD
8
9this.setState(prevState => ({
10 jasper: { // object that we want to update
11 ...prevState.jasper, // keep all other key-value pairs
12 name: 'something' // update the value of specific key
13 }
14}))
1import React, { useState } from 'react'
2const Example = () => {
3 const [ account, setAccount ] = useState({ username: "", password: "" })
4 return(
5 <div>
6 <p>Debug { JSON.stringify(account) }
7 <form>
8 <input
9 text="text"
10 placeholder="Username"
11 onChange={(e) => {
12 setAccount({ ...account, username: e.terget.value })
13 }}
14 />
15 </br>
16 <input
17 text="text"
18 placeholder="Password"
19 onChange={(e) => {
20 setAccount({ ...account, password: e.terget.value })
21 }}
22 />
23 </form>
24 </div>
25 )
26 }
27
28 https://www.youtube.com/watch?v=nWGcOTyTkQ0&t=457s
1this.setState(prevState => ({
2 food: {
3 ...prevState.food, // copy all other key-value pairs of food object
4 pizza: { // specific object of food object
5 ...prevState.food.pizza, // copy all pizza key-value pairs
6 extraCheese: true // update value of specific key
7 }
8 }
9}))
1this.state = {
2 jasper: { name: 'jasper', age: 28 },
3}
4
5this.setState({
6 jasper: {
7 ...this.state.jasper,
8 name: 'something'
9 }
10})