I've got town value (in an object) like:
75000 - Paris Ile-de-France
I'm trying to get the second part of my town state value using the split method:
<Text>{this.state.town.split("-")[1].trim() || ''}</Text>
But it seems split method is taken as an element of the object. I've got this error:
Cannot read property 'split' of undefined.
Any idea?
UPDATE :
Ok, it's undefined at start point, before I update the state of town.
Now I try to put a condition before it tries to split my string, but I fail. I'm doing this, but it returns an unexpected token:
<Text style={styles.selectedTown}>{
return (this.state.town !== {}) ? this.state.town.split('-')[0].trim() : '';
}</Text>
I've got town value (in an object) like:
75000 - Paris Ile-de-France
I'm trying to get the second part of my town state value using the split method:
<Text>{this.state.town.split("-")[1].trim() || ''}</Text>
But it seems split method is taken as an element of the object. I've got this error:
Cannot read property 'split' of undefined.
Any idea?
UPDATE :
Ok, it's undefined at start point, before I update the state of town.
Now I try to put a condition before it tries to split my string, but I fail. I'm doing this, but it returns an unexpected token:
<Text style={styles.selectedTown}>{
return (this.state.town !== {}) ? this.state.town.split('-')[0].trim() : '';
}</Text>
Share
Improve this question
edited Jun 10, 2016 at 13:50
Xavier C.
asked Jun 10, 2016 at 13:30
Xavier C.Xavier C.
1,8174 gold badges25 silver badges40 bronze badges
4
-
3
this.state.town.name
isundefined
– Pranav C Balan Commented Jun 10, 2016 at 13:31 - Sorry I made corrections. – Xavier C. Commented Jun 10, 2016 at 13:32
-
1
What does your state look like at that point in time? The error would seem to indicate that there's no
town
property inside of your state. – ajm Commented Jun 10, 2016 at 13:37 - 3 Again, this means that town is undefined. Please show that code that you use to intialize this.state. – Cobus Kruger Commented Jun 10, 2016 at 13:37
1 Answer
Reset to default 2There is a difference between undefined and defined as an empty object. Try this:
<Text style={styles.selectedTown}>{
(this.state.town !== undefined) ? this.state.town.split('-')[0].trim() : ''
}</Text>