Reputation: 35
constructor(props) {
super(props)
this.state = {
per_name:'',
per_email:'',
person:{
name:'',
email:'',
array:[]
}
}
}
this.setState({
person:{
name:this.state.per_name,
email:this.state.per_email
}
})
I'm new to react if i try to setstate in this manner "per_name is not defined" error is thrown. How should state be set in such a case??
Upvotes: 2
Views: 275
Reputation: 1479
You can follow this practice for more clearance
constructor(props) {
super(props)
this.state = {
per_name:'',
per_email:'',
person:{
name:'',
email:'',
array:[]
}
}
}
someMethod() {
const {person, per_name, per_email} = this.state;
person.name = per_name;
person.email = per_email;
this.setState({
person
});
}
Upvotes: 1
Reputation: 1
You should keep the non modified keys by using spread operator :
this.setState({
...this.state,
person:{
...this.state.person,
name:this.state.per_name,
email:this.state.per_email
}
})
Upvotes: 3