how to read Realtime firebase data (ref.on is not a function )? - javascript

use next.js
update and set work without problems, but when I want to read using on, an error occurs, in the settings firebase checked for me read and write = true
import { getDatabase,ref,set,once,on,update,onChildAdded} from 'firebase/database';
const reference = ref(db, 'room/' + 'new');
// get support data from firebase
reference.on('value',function (snapshot) {
console.log("In Value");
console.log(snapshot.val());
}, function(error) {
console.error(error);
});
I get an error
reference.on is not a function at startSubmit
my firebase

There is a onValue() function in the new Modular SDK to listen for updates at the database reference. Try refactoring the code like this:
import { getDatabase, ref, onValue} from "firebase/database";
const reference = ref(db, 'room/' + 'new');
onValue(reference, (snapshot) => {
const data = snapshot.val();
console.log(data)
});
Checkout the documentation for more information.

Related

Firebase Realtime data is only available after saving the edited source file?

I'm relatively new to RN / Javascript, so this might be a rookie mistake - strangely I couldn't find anything close to it on my research.
My setup: I'm developing a RN app with Expo and I'm using the Expo Go app to see any changes.
Since I want to enable cloud services, I'm using the Firebase Realtime database with the official packages in my app. So far, so good.
My issue: Every time I start the developement server (npm start) or reload the app with the 'r' shortcut on my Accounts screen (basic screen displaying the names of the accounts the user created), see attached screenshot, the app refuses to load the data from Realtime - instead I'm greeted with a 'undefined is not an object (evaluating 'obj['accounts']'). Once I hit 'STRG + S' on my keyboard in any file opened, the Expo Go app refreshes and the data is somehow found.
If anyone could help me with this issue, you would surely save my day. :)
CODE
My data is loaded from here (dataHandler.js):
// auth stuff
import { Auth, getAuth } from "firebase/auth";
// database stuff
import { db } from "./firebase";
import { get, onValue, ref } from 'firebase/database'
// more auth stuff
const auth = getAuth()
const userID = auth.currentUser?.uid;
// database Path for retrieving data
const databasePath = userID
export var cachedData = {};
// Gets data from the firebase server, set's it to a local value
export function getData() {
return onValue(ref(db, databasePath), querySnapshot => {
let data = querySnapshot.val() || {};
let downloadedData = {...data};
// set data to a public var
cachedData = downloadedData;
console.log('DEBUG: Data loaded from the server')
})
}
My account data is then loaded from here (accountData.js):
// load the data from dataHandler.js
import { cachedData } from "./dataHandler";
import { getAuth } from "firebase/auth";
const auth = getAuth()
const userID = auth.currentUser?.uid;
export function getAccountData() {
console.log('accountData receives = ', cachedData)
let obj = cachedData[userID];
let accounts = obj['accounts'];
console.log('getAccountData returns: ', accounts)
return accounts;
}
I'm calling the files here:
// experimental stuff
import { getData } from '../../core/dataHandler';
import { getAccountData } from '../../core/accountData'
const Accounts = () => {
// Downloads data on the app start
getData();
// load the data for the account
const accounts = getAccountData()
console.log('accountData = ', accounts)
const accountKeys = Object.keys(accounts)
const [ accountName, setAccountName ] = useState('')
return( <SomeView /> )
}

firebase realtime database undefined function

I'm trying to retrieve from a realtime db I started by init the app with the configuration like so
import {initializeApp} from 'firebase/app';
import {getDatabase} from 'firebase/database';
let config = {
apiKey: 'xxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxx',
...
};
const app = initializeApp(config);
const database = getDatabase(app);
then when I try using the database variable it crashes
componentDidMount() {
database
.ref(`master/tickets`)
.once('value', snapshot => {
var obj = snapshot.val();
console.log('obj :', obj);
})
.catch(error => {
console.log(error);
});
}
I also have tried firebase.database.ref() it shows error cannot find variable firebase
What I am doing wrong? It was working fine in previous builds
The Firebase Web SDK underwent major breaking changes with the update to V9.0.0.
Please see the upgrade guide for details on how to modify older patterns to the new API.
import { ref, get } from "firebase/database";
import { database } from "...";
/* ... */
componentDidMount() {
get(ref(database, 'master/tickets'))
.then(snapshot => {
const obj = snapshot.val();
console.log('obj :', obj);
})
.catch(error => {
console.log(error);
});
}

How to fetch data from Firebase Database with react native? (Warining: Error: child failed: path argument was an invalid path)

I have a managed workflow expo project (Javascript 9) where I want to read my data from Firebase database. I succesfully managed to implement firestore but the database is giving me rough times.
This is my code to Fecth the data:
export const fetchEmployees = async () => {
const rootRef = await dbref(db_realtime,"Employees");
const query = get(query(child(rootRef))).then((result) =>{
console.log(result)
})
}
This is the warning I get:
[Unhandled promise rejection: Error: child failed: path argument was
an invalid path = "undefined". Paths must be non-empty strings and
can't contain ".", "#", "$", "[", or "]"]
And this is how the data looks like in my Firebase Database storage:
Hope this example will help you. It will return all employees details -
const getdata = await db.ref('Employees').once('value',function(snapshot){
console.log(snapshot.val)
}
Here db is your firebase.database().
If it's not working use 'Employees/'.
EDITED -
For 9 -
import { getDatabase, ref, onValue} from "firebase/database";
const db = getDatabase();
const employeeRef = ref(db, 'Employees');
onValue(employeeRef , (snapshot) => {
console.log(snapshot.val());
});

Firebase Realtime database showing strange behavior

I am using react-native-firebase in an ejected expo app and trying to build a presence detection system in my chat app which will detect that if the message recipient is online and if not when was he/she was last online. The data will be stored as follows in firebase realtime database:
{
lastSeen:[{
[userId]:{
state: boolean
time: serverTimeStamp
}
}]
}
The problem is that firebase console never shows the data and only if recipient is online then app shows this data (even though its not visible in console) but if user is offline then nothing is returned and no error generated. I have set read and write to true in realtimeDB rules. Here is the code I am using:
import database from "#react-native-firebase/database";
export const updateUserLastSeen = (userId) => {
const userStatusDatabaseRef = database().ref("/lastSeen/" + userId);
console.log("updatelast", userId);
userStatusDatabaseRef
.set({
state: true,
time: database.ServerValue.TIMESTAMP,
})
.then(() => console.log("online"))
.catch((e) => console.log(e));
// database()
// .ref(".info/connected")
// .on("value", function (snapshot) {
// if (snapshot.val() == false) {
// return;
// }
userStatusDatabaseRef
.onDisconnect()
.set({
state: false,
time: database.ServerValue.TIMESTAMP,
})
.then(function () {
console.log("disconnect configured");
// userStatusDatabaseRef.set({
// state: true,
// time: database.ServerValue.TIMESTAMP,
// });
});
// });
};
export const checkUserLastSeen = (userId, setUserLastSeen) => {
console.log("check last", userId);
database()
.ref("/lastSeen/" + userId)
.on("value", (snapshot) => {
setUserLastSeen(snapshot.val());
console.log("User data: ", snapshot.val());
});
console.log("after check last");
};
I tried both the code from firebase docs and rnfirebase docs. In above code, none of the "then" or "catch" functions get called in updateUserLastSeen but in checkUserLastSeen "on" is invoked only if bearer of userId is online. Also, I am using realtime db only for this purpose and cloud firestore for other data storing and its working fine.
Any help would be appreciated. Thanks.
If neither then nor catch of a write is called, it typically means that the client is not connected to the server.
I recommend checking to make sure your app has a network connection, and that you've configured the (correct) URL for your database.

firebase cloud functions Cannot read property 'ref' of undefined

when i want to update Cloud Firestore from Realtime Database i deployed bellow code and i get error.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const firestore = functions.firestore;
exports.onUserStatusChange = functions.database
.ref('/status/{userId}')
.onUpdate(event => {
var db = admin.firestore();
//const usersRef = firestore.document('/users/' + event.params.userId);
const usersRef = db.collection("users");
var snapShot = event.data;
return event.data.ref.once('value')
.then(statusSnap => snapShot.val())
.then(status => {
if (status === 'offline'){
usersRef
.doc(event.params.userId)
.set({
online: false,
last_active: Date.now()
}, {merge: true});
}
})
});
TypeError: Cannot read property 'ref' of undefined
at exports.onUserStatusChange.functions.database.ref.onUpdate.event (/user_code/index.js:18:20)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:733:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
It looks like you got the code for a beta version of Cloud Functions for Firebase. The syntax has changed in the 1.0 version. From the documentation on upgrading your Cloud Functions:
or onWrite and onUpdate events, the data parameter has before and after fields. Each of these is a DataSnapshot with the same methods available in admin.database.DataSnapshot. For example:
Before (<= v0.9.1)
exports.dbWrite = functions.database.ref('/path').onWrite((event) => {
const beforeData = event.data.previous.val(); // data before the write
const afterData = event.data.val(); // data after the write
});
Now (>= v1.0.0)
exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
const beforeData = change.before.val(); // data before the write
const afterData = change.after.val(); // data after the write
});
So you will want to use:
.onUpdate((change, context) => { to declare the funtcion, instead of .onUpdate(event => {
use change.after to refer to the data, instead of event.data
use change.after.ref.once('value'), instead of event.data.ref.once('value')
Since it seems that this code is mostly copied from somewhere, I'd recommend getting an updated version from there. For example, the Firestore documentation that your code is likely based on, contains an up-to-date example here: https://firebase.google.com/docs/firestore/solutions/presence#updating_globally
Try to change below code, as firebase functions on events have two properties any more. So, ref position is:
.onUpdate((event,context) => {
....
return event.ref.once('value')
...
event.data does not exist anymore, instead event.val() for more info and event has properties like

Categories

Resources