setstate with object react code example
Example 1: Updating an object with setState in React
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper);
jasper.name = 'someothername';
return { jasper };
})
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
Example 2: setstate find opject in state and update
this.setState(prevState => ({
food: {
...prevState.food,
pizza: {
...prevState.food.pizza,
extraCheese: true
}
}
}))
Example 3: react setstate object
import React, { useState } from 'react'
const Example = () => {
const [ account, setAccount ] = useState({ username: "", password: "" })
return(
<div>
<p>Debug { JSON.stringify(account) }
<form>
<input
text="text"
placeholder="Username"
onChange={(e) => {
setAccount({ ...account, username: e.terget.value })
}}
/>
</br>
<input
text="text"
placeholder="Password"
onChange={(e) => {
setAccount({ ...account, password: e.terget.value })
}}
/>
</form>
</div>
)
}
https://www.youtube.com/watch?v=nWGcOTyTkQ0&t=457s
Example 4: react native setstate object
this.setState({
lang1:{
...this.state.lang1,
name: "myExample"
}
})