Home > Software engineering >  Firebase save function error when updating database
Firebase save function error when updating database

Time:09-29

I am trying to update my price and I keep getting this error upon clicking the save button. This is the error code I'm getting:

Uncaught ReferenceError: user is not defined at updatePrice (settings.js:52:43) at HTMLButtonElement.onclick (VM148 settings.html:284:132)

I have provided my js below. This is how i'm calling my function in html as well:

<button  type="submit" id="save11" value="save11" onclick="updatePrice()">Save</button>

JS updated:

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize variables
const database = firebase.database();
const auth = firebase.auth();

firebase.auth().onAuthStateChanged((user) => {console.log(user);});


function updatePrice() {
    //Get data
    numberInput = document.getElementById("numberInput").value;

    const user = firebase.auth().currentUser;

    //Enter database location
    firebase
        .database()
        .ref(user.uid   "/prices/roomA/serviceOne")
        .update({

            //studioName : studioName,
            numberInput: numberInput,
        });
}

enter image description here

CodePudding user response:

As a matter of fact user is not defined in the updatePrice() function. In your code, it's only within the callback function passed to the onAuthStateChanged() observer that user is defined.

You need to use the currentUser property as follows:

function updatePrice() {
    //Get data
    numberInput = document.getElementById("numberInput").value;

    const user = firebase.auth().currentUser;

    //Enter database location
    firebase
        .database()
        .ref("/studiopick/studio/users"   user.uid   "/prices/roomA/serviceOne")
        .update({

            //studioName : studioName,
            numberInput: numberInput,
        });
}

However you need to take into account that currentUser could be null. This can happen if the auth object has not finished initializing (more info by reading the entire following documentation section).

So for example, before calling this function, check that firebase.auth() is not null. If it is the case, you can retry in some few seconds or indicate the user to try later.

  • Related