0
I cannot use state helps once the page is rendered. The following error appears:
TypeError: undefined is not an object (evaluating 'this.state.ajudas['0']['tipo']')
My code:
class AjudaScreen extends Component {
constructor(props) {
super(props);
this.state = { ajudas: '' }
this.getAllAjudas = this.getAllAjudas.bind(this)
this.getAjudas = this.getAjudas.bind(this)
this.getAllAjudas()
}
getAllAjudas() {
firebase.db.ref('ajudas/').once('value').then((dados) => {
this.getAjudas(dados.val())
})
}
getAjudas(ajudas) {
this.setState({ ajudas: ajudas })
}
componentDidUpdate(prevState) {
if (this.state.ajudas !== prevState.ajudas) {
console.log("UPDATE =====> " + this.state.ajudas['0']['tipo']);
}
}
render() {
return (
<ScrollView>
<View style={{
flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#feddc7'
}}>
<Text style={
{
color: '#FA7921',
fontSize: 25,
margin: 25
}
}>{this.state.ajudas['0']['tipo']}</Text>
<Image source={require('./carta-analista.png')} style={styles.imagem} />
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Vamos La!')}>
<View style={styles.button}>
<Text style={styles.buttonText}>USAR AJUDA</Text>
</View>
</TouchableOpacity>
</View>
<View style={{
flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#feddc7'
}}>
<Text style={
{
color: '#FA7921',
fontSize: 25,
margin: 25,
}
}>Programador</Text>
<Image source={require('./carta-programador.png')} style={styles.imagem} />
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Vamos La!')}>
<View style={styles.button}>
<Text style={styles.buttonText}>USAR AJUDA</Text>
</View>
</TouchableOpacity>
</View>
</ScrollView>
)
}
}
export default class Game extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Tab.Navigator
tabBarOptions={{
activeTintColor: '#FA7921',
inactiveTintColor: 'gray',
}}>
<Tab.Screen name="Classificar" component={ClassificarScreen} />
<Tab.Screen name="Bônus" component={BonusScreen} />
<Tab.Screen name="Ajudas" component={AjudaScreen} />
</Tab.Navigator>
)
}
}
When you access using the index
ajudas[0]
, it may happen that during the state update this element does not exist, therefore when you try to access the propertytipo
it generates error. Ideally you iterate this array withmap
for example, because there won’t be this problem with indexes.– Camilo Santos