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

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>

Related

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!

TypeError: firebase.firestore () is not a function web javascript

I am trying to upload an image on firebase cloud storage with web javascript. I am getting "firebase.firestore () is not a function" on my console. Am I going any wrong way?
I have done insert and fetch data on firebase database. But I have to stop for upload image on firebase cloud storage.
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.3.0/firebase-firestore.js"></script>
var firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX"
};
// Initialize Firebase
var defaultProject = firebase.initializeApp (firebaseConfig);
// Get a reference to the database service
var fileName = selectedFile.name;
var storageRef = firebase.firestore ().ref ('image' + fileName).put (selectedFile);
updating node on the computer seemed to have fixed the issue. I updated it to v16.15.1
change
firebase.firestore ().ref ('image' + fileName).put (selectedFile);
to
firebase.storage().ref('image' + fileName).put (selectedFile);

I receive: firebase.database is not a function error when trying to connect my form to the database

I'm trying to connect my contact form to a firebase database and i keep getting the firebase.database is not a function error continuously.
I'm also using parcel-bundler for this project and also getting these errors:
at Object.parcelRequire.firebase.js (firebase.js:44)
at newRequire (firebase.js:44)
at firebase.js:44
at firebase.js:44
I really don't know what I'm doing wrong, after looking at similar problems none of them could provide a solution.
This is how I am linking my files:
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>
<script src="./firebase.js"></script>
<script src="./main.js"></script>
</body>
This is the code from my firebase.js file:
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaS*************r48uEU",
authDomain: "k********irebaseapp.com",
databaseURL: "https://*******irebaseio.com",
projectId: "k******",
storageBucket: "k**********m",
messagingSenderId: "984****903",
appId: "1:9843179**********3734705af"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var messageRef = firebase.database().ref("messages");
//grab a form
document.querySelector(".contact-form").addEventListener("submit", submitForm);
function submitForm(e) {
e.preventDefault();
// get values
var name = getInputVal("name");
var email = getInputVal("email");
var number = getInputVal("phone");
var message = getInputVal("message");
saveMessage(name, email, number, message);
}
function getInputVal(id) {
return document.getElementById(id).value;
}
function saveMessage(name, email, number, message) {
var newMessageRef = messageRef.push();
newMessageRef.set({
name: name,
email: email,
number: number,
message: message
});
}
Any help will be deeply appreciated, thanks guys.
You're currently only including this for Firebase:
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>
This only contains the definition of FirebaseApp, and doesn't include Firebase Authentication (firebase.auth()) or Firebase Realtime Database (firebase.database()). To include those, be sure to include the correct scripts for that too:
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-database.js"></script>

Javascript - Cannot instantiate firebase-firestore

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>

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