Subham Ghosh
Subham Ghosh

Reputation: 13

React native Reference child failed

const { width: WIDTH } = Dimensions.get('window');
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
    dd = '0' + dd;
}
if (mm < 10) {
    mm = '0' + mm;
}
today = mm + dd + yyyy;

class Attendance extends Component {
    state = {
        image: null,
        submit: false,
        loading: false,
        face: null,
        confidence: 0,
        class: '',
        flag: ''
    };
    async componentDidMount() {
        await Permissions.askAsync(Permissions.CAMERA);
        const { currentUser } = firebase.auth();
        firebase
         .database()
         .ref('users/')
         .child(currentUser.uid)
         .on('value', snap => 
            this.setState({ 
                face: snap.val().image,
                class: snap.val().stream_sem
            })
         );
    }
    render(){
        return(
            <View style={styles.Conatiner}>
                <Loader loading={this.state.loading} />
                {this.renderContent()}
            </View>
        );
    }
    renderContent = () =>  {
        firebase.database().ref('attendance')
        .child(this.state.class)
        .child(today)
        .on("value", snap => {
            this.setState({ flag: snap.val().flag});
        });
        if(this.state.flag === "0") {
            //**something**
        }
        else {
            //**something**
        }
    }
}

When i am trying to write this.state.class, it is showing reference child failed. Here is the error detail i am getting. My firebase database Picture is here. Can you please tell where i am going wrong. I want to access "flag" part of the database. CSE8 should match with the users stream_sem ThankYou in advance

Upvotes: 0

Views: 96

Answers (1)

Tech Alpha Studios
Tech Alpha Studios

Reputation: 139

When your renderContent is called first time, your state.class is empty string, remember that firebase snapshot will be loaded asynchronously. Also, do not attach listeners to firebase in a render function that is called by render method, you will end up having a lot of listeners.

Your logic should be something like:

  1. Get user data from firebase
  2. If data is not null, set state
  3. After state is set, get attendance data from database
  4. Set state appropriately

Always write rough algorithm before jumping state to dev (Ignore if you already knew that). Happy learning, Cheers!

Upvotes: 1

Related Questions