简体   繁体   中英

Update 2 children in firebase realtime database with react native

Im trying to update two children in my database (using realtime database firebase), but when database is updated, my application go back to the home screen for no reason.

When I update only in "Tasks" it works (the app doesnt go back to the home screen) but when I combine update in "Tasks" and "Users" there is this problem.. Maybe i dont do it the good way.. Any ideas?

statusPlayback = async (status) => {
    const { navigation } = this.props
    const task = navigation.getParam('task')
    //console.log("task = ", task);



    //to check if we arrived to the end of the
    if (status.didJustFinish) {

        const CountVideoRef = firebase
            .database()
            .ref("Tasks")
            .child(firebase.auth().currentUser.uid).child(task.AssignPerson)
            .child(task.taskname);

        CountVideoRef.once("value").then((snapshot) => {
            CountVideoRef.update({
                countViewVideo: snapshot.val().countViewVideo + 1,
            });
           
        })

       const PointEndVideoRef = firebase
                .database()
                .ref("Users")
                .child(firebase.auth().currentUser.uid);

            PointEndVideoRef.once("value").then((snapshot1) => {
                PointEndVideoRef.update({
                    Points: snapshot1.val().Points + 10,
                });

                const points = (snapshot1.val().Points) + 10
                //console.log("points = ", points)
                this.props.updatePoints({ points: points })
            })




        this.setState({ showButtonVisible: true });
    }
};

I doubt this is the cause of the navigation problem, but this style of updating is fraught with problems:

CountVideoRef.once("value").then((snapshot) => {
    CountVideoRef.update({
        countViewVideo: snapshot.val().countViewVideo + 1,
    });
   
})

If you need to update an existing value in the database based on its existing value, you should use a transaction to prevent race conditions when multiple users perform the same action around the same time (or while offline).

In this case, you can use the simpler atomic server-side increment operation, which means the above becomes:

CountVideoRef.set(firebase.database.ServerValue.increment(1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM