Reputation: 59
I have an issue with state key that I want to set it only if other states have the value of X.
this.state = {
//display items
setLanguage:'eng',
language:this.state.setLanguage=='eng'?Language.eng:Language.heb,
If I set the language to this.state I get the all state keys and values, but if I try to set it to
language:this.state.setLanguage
I get the error:
TypeError: undefined is not an object (evaluating '_this.state.setLanguage')
Upvotes: 2
Views: 219
Reputation: 1808
You're trying to use a state that has not been set. The correct code should be:
this.state = {
setLanguage,
language: setLanguage === 'eng' ? Language.eng : Language.heb
}
There's another way, that is to set the new state using a callback.
this.setState({ setLanguage }, () => { this.setState({ language: this.state.setLanguage === 'eng' ? Language.eng : Language.heb }); });
Note that this.state.setLanguage
is available inside the callback because the state has been already set in the first call.
Upvotes: 2