Uncaught Error: Service database is not available firebase javascript - javascript

I am trying to access my realtime database in firebase but it shows me this error Uncaught Error: Service database is not available. I have searched for what this could posabbly mean but I couldn't find anything useful or a solution.
Here is my code:
window.addPerson = addPerson;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userVar = urlParams.get('user')
const userVarSplitted = userVar.split('#')
const userVarFormatted = userVarSplitted[0] + ":" + userVarSplitted[1]
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-analytics.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {MY FIREBASE CONFIG};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
if (app.length === 0) {
console.log("no firebas app")
}else{
console.log("initialized")
}
const analytics = getAnalytics(app);
const database = getDatabase(app);
function addPerson() {
set(ref(database, "verified/" + userVarFormatted), {
name: userVarSplitted[0],
discriminator: userVarSplitted[1]
});
console.log("added")
PS: The script type is set to modular.
Do you know what the error means and what is happening?

You're using difference versions of the Firebase SDKs. I'd update the database import to version 9.6.4 too, so that the all Firebase SDK versions are the same.

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 /> )
}

How to fix error that my Vue app doesn't get data from Firebase?

I made a Firebase app with database, connected it with Vue app, which is like todo-list. I tried to get a data from database from firebase, which is used to make components for app, but something got wrong. Vue app doesn't get the data from firebase, so items aren't created
It's th error:
#firebase/firestore: Firestore (9.10.0): Uncaught Error in snapshot listener: {"code":"permission-denied","name":"FirebaseError"
Initializing firebase:
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import { getFirestore } from "#firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyBZlP_E74i40ZLopttFlUbg3j36wirKf9A",
authDomain: "quotes-app-8788c.firebaseapp.com",
projectId: "quotes-app-8788c",
storageBucket: "quotes-app-8788c.appspot.com",
messagingSenderId: "934346412075",
appId: "1:934346412075:web:5da2928fecb05c834f5a6e"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export {
db
}
Here is my code:
onSnapshot(collection(db, 'quotes'), (QuerySnapshot) => {
const fbquotes = [];
QuerySnapshot.forEach((doc) => {
const quote = {
id: doc.data().id,
quoteText: doc.data().quoteText,
quoteAuthor: doc.data().quoteAuthor,
quoteGenre: doc.data().quoteGenre,
timeCreating: doc.data().timeCreating,
timeEditing: doc.data().timeEditing
}
this.fbquotes.push(quote)
})
this.quotes = fbquotes
console.log(this.quotes);
})
console.log(this.quotes);
},
The error code "permission-denied" tells that your security rules are not allowing the user to query that whole collection. If a user can read all documents from the "quotes" collection then make sure you have the following rules:
match /quotes/{quotesId} {
allow read: if true;
}
You can change the condition for allow read if your requirements are different. Also Security Rules are not filters so if you want to allow a user to read their own documents only, then make sure you change the query in your code as well to match the security rules.

firebase is not being recognized in Unity webGL Build

I have set up a test project in order to test Firebase with unity webGL builds.
I have created a *.jslib plugin to keep my js functions in there :
mergeInto(LibraryManager.library, {
GetJSON: function (path, objectName, callback, fallback) {
var parsedPath = Pointer_stringify(path);
var parsedObjectName= Pointer_stringify(objectName);
var parsedCallback = Pointer_stringify(callback);
var parsedFallback = Pointer_stringify(fallback);
try{
firebase.database().ref(parsedPath).once('value').then(function(snapshot) {
window.unityInstance.SendMessage(parsedObjectName, parsedCallback , JSON.stringify(snapshot.val()));
});
} catch(error){
window.unityInstance.SendMessage(parsedObjectName, parsedFallback, "There was an error: " + error.message);
}
}
});
After building and running, I add my Firebase config snippet into the index.html file(I have hidden the actual keys on this snippet):
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "key",
authDomain: "domain",
projectId: "id",
storageBucket: "bucket",
messagingSenderId: "senderID",
appId: "appId",
measurementId: "measurementId"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
In unity, I am testing this by calling the GetJSON function, and I have a callback, and a fallback method:
void Start()
{
text.text = "Start worked";
GetJSON(path: "example", gameObject.name, callback: "OnRequestSuccess", fallback: "OnRequestFailed");
}
public void OnRequestSuccess(string data)
{
text.color = Color.green;
text.text = data;
}
public void OnRequestFailed(string error)
{
text.color = Color.red;
text.text = error;
}
After I have built and run my webGL project, and updated the index.html file with the proper configurations, the text turns red (Which means the OnRequestFailed() was called) and it says: "There was an error: firebase is not defined". Which means, it does not recognize the firebase when I use it on the *.jslib plugin. Where should the firebase be defined exactly? Because I am defining it in my index.html, or at least I think so?

Cannot import Firebase Firestore Colletion

I'm trying to call a Firestore Colletion in my next app, here is the error that I get when running the app:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
Here is my firebase.js code:
import firebase from 'firebase/app';
import "firebase/firestore"
const firebaseConfig = {};
export const getPosts = async () => {
firebase.initializeApp(firebaseConfig);
const posts = await firebase.firestore().collection("articles").then((snapshot) => {
const snapshotVal = snapshot.val();
const result = [];
for (var slug in snapshotVal) {
const post = snapshotVal[slug];
result.push(post);
}
return result.reverse();
});
return posts
};
Because you keep trying to initialize a new firebase app every time you getPosts, so you should check first if there isn't a firebase app before initializeApp,
try something like this before getPosts function:
var firebase_app;
if (!firebase.apps.length) {
firebase_app = firebase.initializeApp(firebaseConfig);
} else {
firebase_app = firebase.app(); // if already initialized, use that one
}

weird behavior await running without async

I was running firebase when I saw a strange behavior which I am unable to understand. My html looks like this:
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-firestore.js"></script>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp, } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getFirestore, collection, getDocs, addDoc } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
const firebaseConfig = { ... } //firebase config
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const querySnapshot = await getDocs(collection(db, "location")); *** //await is running without async! ***
console.log(querySnapshot)
querySnapshot.forEach((doc, index) => {
// do something with doc
*** // index always returns undefined! ***
}
Problem 1: Async running without await.
Problem 2: Index is undefined after reading and iterating data from firebase.
Please help as I studied js for more than a year and I feel like a complete newbie now.
Thank You Bergi (Profile):
It is indeed a top level await (a feature in moduleJS).
Read more about it here: https://v8.dev/features/top-level-await
Thanks! Dharamraj (Profile) => querySnapshot.docs.forEach() index works perfectly fine now.

Categories

Resources