I need to update the 'status' field in Firebase for the item selected in the Flatlist. When an item is selected, a popup appears and the user can select 'Completed?' or 'Failed?'. An error occurs when the code runs 'goalComplete' and 'goalFailed' functions, because the Firebase reference fails to connect with the correct path. The 'onRenderItem' function prints the correct key on 'item.key'.
The error is "Cannot read property of 'key' of undefined", which occurs when 'goalComplete' or 'goalFailed' runs.
The 'goal' and 'status' fields were put in Firebase using the .push function, which generate the key that I'm trying to reference in the Firebase path, one level above 'goal' and 'status' for each item.
I would really appreciate your help with this.
import React, { Component } from 'react';
import { Text, FlatList, View, Image, TouchableOpacity, Alert } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection } from '../common';
import styles from '../Styles';
class List extends Component {
static navigationOptions = {
title: 'List',
}
constructor(props) {
super(props);
this.state = {
goallist: '',
loading: false,
};
}
componentDidMount() {
this.setState({ loading: true });
const { currentUser } = firebase.auth();
const keyParent = firebase.database().ref(`/users/${currentUser.uid}/goalProfile`);
keyParent.on(('child_added'), snapshot => {
const newChild = {
key: snapshot.key,
goal: snapshot.val().goal,
status: snapshot.val().status
};
this.setState((prevState) => ({ goallist: [...prevState.goallist, newChild] }));
console.log(this.state.goallist);
});
this.setState({ loading: false });
}
onRenderItem = ({ item }) => (
<TouchableOpacity onPress={this.showAlert}>
<Text style={styles.listStyle}>
{ item.goal } { item.key }
</Text>
</TouchableOpacity>
);
goalComplete = ({ item }) => {
const { currentUser } = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/goalProfile/${item.key}`).update({
status: 'Done'
});//this is not updating status in Firebase for the item selected (get 'key is undefined)'
}
goalFailed = ({ item }) => {
const { currentUser } = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/goalProfile/${item.key}`).update({
status: 'Fail'
});//this is not updating status in Firebase for the item selected (get 'key is undefined)'
}
showAlert = () => {
Alert.alert(
'Did you succeed or fail?',
'Update your status',
[
{ text: 'Completed?',
onPress: this.goalComplete
},
{ text: 'Failed?',
onPress: this.goalFailed
},
{ text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel' },
],
{ cancelable: false }
);
}
keyExtractor = (item) => item.key;
render() {
return (
<Card>
<View style={{ flex: 1 }}>
<FlatList
data={this.state.goallist}
keyExtractor={this.keyExtractor}
extraData={this.state}
renderItem={this.onRenderItem}
/>
</View>
</Card>
);
}
}
export { List };