简体   繁体   中英

ReactJS onClick function is not triggering correctly

Function is ONLY triggering correctly if I add e.preventDefault(). However, I want it to push the user to '/' after the user submits the form. Here is the function I am trying to trigger:

onAddPoints = (e) => {
    e.preventDefault();
    //history.push('/');
    let { phoneNumber, points, onPointsChange } = this.state;

    //convert string to int -> calculate update points
    let p1 = Number(points);
    let p2 = Number(onPointsChange);
    const updatedPoints = p1 + p2; 

    //update points
    firebase.auth().onAuthStateChanged((user) => {
        if(user) {
            const docRef = database.collection('users').doc(user.uid).collection('customers').doc(phoneNumber);
            docRef.update({
                "points": updatedPoints
            }).then(() => {
                console.log('success');
            }).catch((error) => {
                console.log(error);
            })
        } else {
            window.location.href = '/';
        }
    });
}

You need to wait to see the result of your request.

If the request is right then is ok if you send the user to another page but if the request gets an error then you have to tell the user that something is wrong.

firebase.auth().onAuthStateChanged((user) => {
    if(user) {
        const docRef = database.collection('users').doc(user.uid).collection('customers').doc(phoneNumber);
        docRef.update({
            "points": updatedPoints
        }).then(() => {
            history.push('/');
            console.log('success');
        }).catch((error) => {
            console.log(error);
        })
    } else {
        window.location.href = '/';
    }
});

And is ok if you use e.preventDefeault() because it stops the default form action flow onSubmit which is go to the page that is setup in the action='./update.php' property. That's commonly used in php apps for example by doing that you send all the inputs info to that update.php .

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