Abdennacer Lachiheb
Abdennacer Lachiheb

Reputation: 4888

react native how to deal with Cannot read property 'undefined' of undefined

I'm expecting some data from remote server to show it in the screen but I got this error in the simulator Cannot read property 'undefined' of undefined the reason why is the content is rendered before the arrival of the results, this the part of code where I'm having this error :

caption = { this.state.customFieldDropdown['gender'][this.state.dropDownSelectedItems['gender'] ] || '---Choose---' }

So the property caption is expecting a text, and to deal with undefined values I added this || '---Choose---' to show text '---Choose---' in case of null but the problem is this.state.dropDownSelectedItems['gender'] is undefined and when this.state.customFieldDropdown access that value it caused the error ( reading property which is undefined)

So how to deal with this issue?

Upvotes: 0

Views: 1815

Answers (2)

TBouder
TBouder

Reputation: 2719

Idx is really good. You can do something like that:

if (idx(this.state, _ => _.customFieldDropdown.gender[_.dropDownSelectedItems.gender]))
    caption = this.state.customFieldDropdown.gender[this.state.dropDownSelectedItems.gender]
else
    caption = '---Choose---'

Upvotes: 0

nehvaleem
nehvaleem

Reputation: 127

You seems to have undefined value higher in the property chain. The || operator will match only last value in the chain, so if for example this.state.customFieldDropdown['gender'] is undefined it will fail.

I'll suggest you to take a look at idx function introduced by React team. More details here: https://facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html

Upvotes: 1

Related Questions