how to update state with setstate 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: how to use setstate
class App extends React.Component {
state = { count: 0 }
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
}
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
}
render() {
return (
<div>
<div>
{this.state.count}
</div>
<button onClick={this.handleIncrement}>Increment by 1</button>
<button onClick={this.handleDecrement}>Decrement by 1</button>
</div>
)
}
}