Firebase save function error when updating database - javascript

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 JavaScript code below. This is how I'm calling my function in HTML as well:
<button class="priceSave" type="submit" id="save11" value="save11" onclick="updatePrice()">Save</button>
JavaScript code 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,
});
}

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 information 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

Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous>)

Description of the problem:
My App aim is to store family spending in Firebase Realtime Database. I want that, when a new spending is stored, a notification is sent to all other devices.
I try to send a notification to a single device and it works fine, but when I try to get all the tokens in an array, I have an error:
TypeError: Cannot convert undefined or null to object at Function.keys ().
code of index.js :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.androidPushNotification = functions.database
.ref("{nodo}/spese/{spesaPush}")
.onCreate(async (snapshot, context) => {
const original = snapshot.val();
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/{tutti}/token`).once('value');
let tokensSnapshot;
let tokens;
tokensSnapshot = await getDeviceTokensPromise;
// This is the line generating the errors.
// If I get only a specific token and
// use tokens = tokensSnapshot.val(); anything works fine
tokens = Object.keys(tokensSnapshot.val());
const result = original.chi + " ha speso " +
original.costo + " € per acquistare " +
original.desc;
console.log(result);
const payload = {
notification: {
title: 'New spending inserted!',
body: result,
}
};
const response = await admin.messaging().sendToDevice(tokens, payload);
return result;
});
It seems that values are not reached yet, but I thought that the keyword await lets system to wait until all data are available. From the log I noticed that the value I need is null and I don't understand why.
If I use this line of code:
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/SpecificUser/token`).once('value');
....
//then
tokens = tokensSnapshot.val();
The notification is sent to the device that has the token under the name of "SpecificUser"
EDIT:
I provide a pic of my db. I notice that none of the field is null, so I don't know why I see this error
Thank you to anyone that helps me
i had same error and it is solve by database...
when i saw my database values unfortunately i stored undefined value so my whole result got error like you...
see your whole values and fields that store values properly.

Firebase onValue doesn't fire and i don't know why

I'm tryin to do a simple web3 app with Next/Js & Firebase.
People can connect with their wallet from solana, to list their NFT, then choose one for connect in a game-container.
I'm stuck because i want to get infos from all connected players listed in Firebase. then with the infos create some div in the game-container with all the connected players.
But, when i try to get the snapshot of all the players, the onValue doesn't fire and i don't know why...
nothing happend, no console log or anything.
That's my code and my database below
const database = getDatabase();
const reference = ref(database,'players/' + playerWallet);
const referenceDatabase = ref(database);
function initGame() {
const allPlayersRef = ref(database,'players/');
onValue(allPlayersRef, (snapshot) => { // NEVEER HAPEND IDK WHYYYYYYYYYYYYYYYY
if (snapshot.exists()){
console.log("Snap Exist");
} else {
console.log("snap is empty");
}
console.log("XXXXXXXXXXXXXXXXXXXXXXXXXX");
//start every change occurs
console.log("SNAP: "+snapshot.val());
players = snapshot.val() || {};
console.log("PLAYERS INFO : "+ players.playerName);
Are you sure the user has permission to read the data? If not, you'll get an error message in the console of where the code executes. Alternatively, you can also detect such a permissions error with:
onValue(allPlayersRef, (snapshot) => {
...
}, (error) => {
console.error(error);
});
You are right.
error handler
I have modified the rules and everything is workin now thanks !

Firebase: How to reference a path in Firebase using a variable

I'm trying to reference a variable in my Firebase Realtime Database, but my console doesn't display the data that I want. The right uid is logged, however, I don't know how to reference the variable called serial.
componentDidMount() {
const uid = this.state.user.uid;
console.log(uid);
const serial = db.ref(uid + "/serial");
console.log(serial);
Here is the console
Here is my database
Thanks in advance!
If I correctly understand your question you want to get the value of the uid/serial node.
By doing const serial = db.ref(uid + "/serial"); you define a Reference. You need to query the data at this Reference, by using the once() or the on() methods.
For example:
const serialRef = db.ref(uid + "/serial");
serialRef.once('value')
.then(function(dataSnapshot) {
console.log(dataSnapshot.val());
});
Note that the once() method is asynchronous and returns a Promise which resolves with a DataSnapshot.
Can you try this:
componentDidMount() {
const uid = this.state.user.uid;
console.log(uid);
const dbItem = db.ref(uid);
console.log(dbItem.serial);
}

Credential from Firebase EmailAuthProvider not working

I use firebase with react then need to convert anonymous account to permanent. I have follow firebase doc but when I try look like cannot use this function they have error message as undefined
in code
let credential = firebase.auth.EmailAuthProvider.credential(email, pass)
error message
Uncaught TypeError: Cannot read property 'credential' of undefined
Someone please help me to fix a problem
ps. in my package
"firebase": "^4.5.0"
First check whether you are anonymously signed in or not.Below code will be helful to do so.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
// ...
} else {
// User is signed out.
// ...
}
// ...
});
If you get some defined values then use EmailAuthProvider to get credentials.
var credential = firebase.auth.EmailAuthProvider.credential(email, password);

Firebase Functions app_remove , get userid

I am trying to create a new entry (with userid) in my firebase database as soon as a user removes my app. (Qndroid)
'use strict';
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
exports.appremoved = functions.analytics.event('app_remove').onLog(event => {
console.log("App remove detected");
var user = admin.auth().currentUser;
var uid;
const uid2 = event.data.user.userId;
console.log("App remove detected2:" + uid2);
if (user != null) {
uid = user.uid;
console.log("User object not empty" );
admin.database().ref('/user_events/'+uid + "/"+Date.now()).set("app_remove");
}
});
I created two variables to get the user id, but both of them are undefined.
uid2 is undefined, and user is null.
I also tried
const user = event.data.user;
But it is also null
How do I get the userid of the user that removed the app?
Calling admin.auth().currentUser gets you the administrative user that is running the admin SDK. This user does not have a UID. And even if they did, it wouldn't be the user that removed the app.
Calling event.data.user.userId gives you the user ID that your app may have set via the setUserId API. If you didn't set a UserId, the call won't give you any value.

Categories

Resources