Javascript - Cannot instantiate firebase-firestore - javascript

Trying to follow the google Getting Started With Cloud Firestore on the Web - Firecasts
For some reason I'm getting this error:
Uncaught Error: Cannot instantiate firebase-firestore - be sure to load firebase-app.js first.
But I believe I have everything done as it should be. What is wrong with this?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-firestore.js"></script>
</head>
<body>
<h1 id="hotDogOutput">Hot dog status:</h1>
<input type="textfield" id="latestHotDogStatus">
<button id="saveButton">Save</button>
<script src="./app.js"></script>
</body>
</html>
Javascript
// Initialize Firebase
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const firestore = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
const docRef = firestore.doc("samples/sandwichData");
const outputHeader = document.querySelector("#hotDogOutput");
const inputTextField = document.querySelector("#latestHotDogStatus");
const saveButton = document.querySelector("#saveButton");
saveButton.addEventListener("click", function () {
const textToSave = inputTextField.value;
console.log("I am going to save " + textToSave + " to Firestore");
docRef.set({
hotDogStatus: textToSave
}).then(function() {
console.log("Status Saved!");
}).catch(function(error) {
console.log("Got an error: ", error)
});
})

Either import the entire firebase.js or just firebase-app.js followed by firebase-firestore.js. What's happening here is that the firebase-firestore.js expects firebase-app.js (The core Firebase client) and not the entire library.
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-firestore.js"></script>
Helpful Guide:
https://firebase.google.com/docs/web/setup

If you are using real time database, then add only these two script srcs:
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>

Related

Retrieve specific values in a Realtime Database - Firebase

My aim is to be able to retrieve certain values from a realtime database on firebase via javascript. I have everything configured and it works perfectly,but I don't know how to retrieve the individual fields when I click a simple button.
This is an example of the values I would like to be able to take
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button type="submit" id="searchData" class="btn btn-primary">Search data</button>
</body>
</html>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js";
import { getDatabase, set, ref ,push, child, onValue} from "https://www.gstatic.com/firebasejs/9.6.8/firebase-database.js";
const firebaseConfig = {
apiKey: "********************************",
authDomain: "********************************",
databaseURL: "********************************",
projectId: "********************************",
storageBucket: "****************************",
messagingSenderId: "******************",
appId: "********************************"
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
searchData.addEventListener('click',(e) => {
//
});
</script>
you can try using this example I always implement, note my main file is users, then my key value as id is userId then I have the attributes username and useremail. Try this:
I want to obtain a name:
const dbRef=ref(db, 'users/'+userId);
onValue(dbRef, (snapshot)=>{
const data=snapshot;
for(let i in data){
console.log(snapshot.val().username);
txtCont.innerHTML=`<p>${snapshot.val().username}</p>`;
}
});

How do I display real-time firebase data on my website?

I am trying to post the data from a moisture sensor on a website. I am using Arduino to update and send the data to a Real-Time Firebase database. From there I am using Glitch.com for my website. I am using a moisture sensor, and have the variable 'Moisture' in my database where the values are stored and updated every 0.3 seconds. I currently have the following code:
HTML File
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
firebase.initializeApp(config);
</script>
<script>
var database = firebase.database();
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "plant-patrol"
var childKey = snapshot.child("plant-patrol/Moisture").key; // "Moisture"
});
</script>
<script>
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
</script>
<script src="/script.js" defer></script>
</head>
</html>
JS File
auth.onAuthStateChanged(currentUser => console.log(currentUser));
auth.signInAnonymously();
I have no idea what this JS code does, but I copied it from another question on Stack Overflow.
Now as stated before, the path in the Realtime Firebase db I want to display is 'Moisture', that is also the only data in the db. I have tried messing around a bit with the childkey and snapshot, and tried reading into what they actually do. Sadly I was not able to display any form of data, not even in the console.
The read & write lines in Firebase have both been set to True as security is not relevant (school project). I was also wondering if it is possible to update the data on the website without having to refresh the page.
Update
Made a bit of progress,read my comments below!

Giving error when retrieving data from Firebase with Javascript

i included these cdn in my html:
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
<script src="StoreFeatured.js" type="text/javascript"></script>
and here is the store featured code
var firebaseConfig = {
apiKey: "$$$$$$$",
authDomain: "$$$$$$",
databaseURL: "https://thegreatpcstore.firebaseio.com",
projectId: "thegreatpcstore",
storageBucket: "thegreatpcstore.appspot.com",
messagingSenderId: "302435893791",
appId: "$$$$$$$",
measurementId: "G-0GH3F41E5S"
};
firebase.initializeApp(firebaseConfig);
new function GetData()
{
firebase.database().ref('/Products/Motherboard/1').once('value').then(function (snapshot) {
//var Description = snapshot.val().Description;
var Name = snapshot.val().Name;
var Price = snapshot.val().Price;
var ImageStr = snapshot.val().ImageStr;
document.getElementById("Mi"+i).src=ImageStr;
document.getElementById("Mn"+i).innerHTML=Name;
document.getElementById("Mp"+i).innerHTML=Price;
}
)
}
what am i doing wrong?
im getting these errors:
> firebase-auth.js:206 Uncaught Error: Cannot find the firebase namespace; be sure to include firebase-app.js before this library.
at firebase-auth.js:206
at firebase-auth.js:206
at firebase-auth.js:206
>
> firebase-database.js:38 Uncaught Error: FIREBASE FATAL ERROR: Failed
> to register the Firebase Database Service (TypeError:
> firebase.INTERNAL.registerService is not a function)
> at dd (firebase-database.js:38)
> at firebase-database.js:245
> at firebase-database.js:245
>
> StoreFeatured.js:17 Uncaught TypeError: firebase.database is not a
> function
> at new GetData (StoreFeatured.js:17)
> at StoreFeatured.js:13
first line of getdata() is doing problem i think im doing something wrong with cdn... please help
if i remove the cdn it gives one error:
StoreFeatured.js:16 Uncaught TypeError: firebase.database is not a function
at new GetData (StoreFeatured.js:16)
at StoreFeatured.js:13
Update both the firebase-auth and firebase-database to the following version:
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-database.js"></script>
Instead of using various CDN use a single CDN which include all the library:
script src="https://www.gstatic.com/firebasejs/7.14.4/firebase.js"

Firebase web app: firebase.database is not a function [duplicate]

This question already has answers here:
firebase.database is not a function
(9 answers)
Closed 3 years ago.
I am working on an application for android that lets people login and add their data for an amusement park and I also need an app to view the data stored in the database (such as name, birthdate, children etc) on a PC. I have tried to write a web app but I have a problem connecting it to the database. I am new to databases so it might be from my code, can someone help me? The app only needs to show me the database all the time and update when a person registers.
Currently, I am getting this error:
Uncaught TypeError: firebase.database is not a function
at index.html:33
at index.html:66
Here is my index.html file:
<html>
<head>
<meta charset="utf-8"/>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-analytics.js"></script>
<title>Freaky Firebase Example</title>
</head>
<body>
<h1>Freaky Firebase Realtime Database Example</h1>
<pre id='object'></pre>
<script>
(function(){
// Initialize Firebase
var firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX.com",
databaseURL: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX.com",
projectId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX.com",
messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var userDataRef = firebase.database().ref("UserData").orderByKey();
userDataRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var name_val = childSnapshot.val().Name;
var id_val = childSnapshot.val().AssignedID;
$("#name").append(name_val);
$("#id").append(id_val);
});
});
/* Data Event Listeners Start */
const preObject = document.getElementById('object');
const dbRefObject = firebase.database().ref().child('object');
dbRefObject.on('value', snap => {
console.log(snap.val());
preObject.innerText = JSON.stringify(snap.val(), null, 3);
}, function(error) {
// The fetch failed.
console.error(error);
});
/* Stop */
}());
</script>
</body>
</html>
Along with firebase-app and firebase-analytics, you must import the firebase-database service.
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-database.js"></script>

Error While Working With Firebase Storage

This is my first attempt working with Firebase storage and I'm following this tutorial provided by Firebase:
https://www.youtube.com/watch?v=SpxHVrpfGgU
I've seem to follow the tutorial step-by-step, however, I'm getting the following error and I can't find a solution for it:
firebase-storage.js:3469 Uncaught Error: No Storage Bucket defined in Firebase Options.
at t.ref (firebase-storage.js:3469)
at HTMLInputElement.<anonymous> (myFile.js:18)
When I click on 't.ref' it leads me to the following catch:
catch(error) {
throw new Error(
'Cannot instantiate firebase-storage.js - ' +
'be sure to load firebase-app.js first.'
)
Here's my HTML:
<!doctype html>
<html lang="en">
<head>
<title>...</title>
<link rel="stylesheet" type="text/css" href="stylesheets.css" />
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "",
messagingSenderId: "..."
};
firebase.initializeApp(config);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav>...</nav>
<progress value="0" max="100" id="uploader" style="margin-top: 35px;">0%</progress>
<input type="file" value="uploader" id="fileButton" />
<script src="myFile.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</body>
</html>
And my corresponding Javascript:
// Get elements
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// Listen for file selection
fileButton.addEventListener('change', function(e) {
// Get file
var file = e.target.files[0];
// Create a storage reference
var storageRef = firebase.storage().ref('mover_docs/' + file.name);
// Upload a file
var task = storage.put(file);
// Update progress bar
task.on('state_changed',
function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err) {
},
function complete() {
}
);
});
I guess my primary question is, is this error occurring since the storageBucket found within the initialize Firebase area has an empty value or am I missing something else?
What needed to be done is copy the link within the 'storage' tab on your Firebase projected above your empty file. It looks something similar to this:
gs://projectName-ci4w0.appspot.com/
Now, just remove the gs:// and the last forward slash after .com. Place this newly formed link into the rules sections in Firebase for Storage like so:
match /b/projectName-ci4w0.appspot.com/o {
Finally, place the same new link within the initialization section for Firebase in your code like so:
<script>
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "projectName-ci4w0.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
</script>
That's it!
In my case, I simply by inattention added white space at the end of bucket URL. Hope somebody will help this because I spent an half of an hour to find this.
storageBucket: "appname.appspot.com "

Categories