Run something after get value from firebase javascript - javascript

I am having a javascript function that gets some value from a node in firebase realtime database. The JS code is:
var numZones;
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var db = firebase.database();
var ref = firebase.database().ref("/LH121");
ref.child("NumZones").once('value', function(snapshot)
{
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
});
console.log('After get value');
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-database.js"></script>
<div class="container" style="text-align: center;">
<div class="row">
<input type="number" name="zones" id="zones" step="1">
</div>
</div>
I want to access something when the get value from firebase is done. How can I do so?

Since .once returns a promise you can chain a .then block to run the code that you want after the .once has been executed.
Reference: https://firebase.google.com/docs/reference/js/firebase.database.Reference#once
ref.child("NumZones").once('value', function(snapshot)
{
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
}).then(() => console.log("After get value"));
I would suggest you to use the following instead of passing a callback function on .once.
ref.child("NumZones").once('value').then((snapshot) => {
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
}).then(() => console.log("After get value"));
More about javascript promises:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Related

Firebase db with vuejs : default.collection is not a function

I'm starting a small project with Vuejs and Firebase. I am trying to upload Name and Price to Firestore. I checked their documentation and few tutorials, but I am stuck with this error.
<div class="form-group">
<v-btn v-on:click="saveData" class="btn btn-primary">Save data</v-btn>
</div>
import db from "../firebase";
export default {
name: "products",
props: {
msg: String,
},
data() {
return {
aon: {
Name: null,
Price: null,
},
};
},
methods: {
saveData() {
db.collection("Products")
.add(this.Product)
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
},
},
};
Here is my firebase.js
import firebase from '#firebase/app';
import '#firebase/auth';
import '#firebase/firestore';
const fb = firebase.initializeApp({
apiKey: "!!!!!!!!!!!",
authDomain: "!!!!!!!!",
databaseURL: "!!!!!!!",
projectId: "!!!!!!",
storageBucket: "!!!!!!!",
messagingSenderId: "!!!!!!!",
appId: "!!!!!!!!!",
measurementId: "!!!!!!!!!!!!"
});
const db = firebase.firestore();
export default firebase;
export {db,fb} ;
First you didn't initialized your firebase app. To do so :
//firebase.js
const db = firebase.initializeApp(fb)
export {db.firestore(),fb}
Then on your products page or component you wrote :
//products.vue
db.collection("Products").add(this.Product)...
this.Product object doesn't exist so it should be this.aon
//products.vue
db.collection("Products").add(this.aon)...
For more info : https://firebase.google.com/docs/firestore/quickstart
As per the documentation here and here you need to use the .set(), .add(), .update() and .doc() methods like this.
When you use set() to create a document, you must specify an ID for the document to create. For example:
await db.collection('cities').doc('new-city-id').set(data);
to let Cloud Firestore auto-generate an ID for you. You can do this by calling add()
// Add a new document with a generated id.
const res = await db.collection('cities').add({
name: 'Tokyo',
country: 'Japan'
});
console.log('Added document with ID: ', res.id);
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc()
const newCityRef = db.collection('cities').doc();
// Later...
const res = await newCityRef.set({
// ...
});
To update some fields of a document without overwriting the entire document, use the update() method:
const cityRef = db.collection('cities').doc('DC');
// Set the 'capital' field of the city
const res = await cityRef.update({capital: true});

Why is the data stored in firestore not being fetched in react?

I am trying to get data from firestore in react but I get the following in console(no data):
t {vf: e, m_: t, xf: null, $f: false, kf: false, …}
$f: false
T_: null
kf: false
m_: t {path: n}
vf: e {uf: n, hf: e, lf: FirebaseAppImpl, _f: e, INTERNAL: {…}, …}
xf: null
exists: (...)
id: (...)
metadata: (...)
ref: (...)
proto: Object
My firebase Setup
import firebase from "firebase";
const firebaseConfig = firebase.initializeApp({
apiKey: "AIzaSyDTpOEQVLZFezpUNDMPmh0FckcQmDQp_rQ",
authDomain: "ecommerce-app-f6a42.firebaseapp.com",
databaseURL: "https://ecommerce-app-f6a42.firebaseio.com",
projectId: "ecommerce-app-f6a42",
storageBucket: "ecommerce-app-f6a42.appspot.com",
messagingSenderId: "455019623318",
appId: "1:455019623318:web:2d90e3539b53ed939663b7",
measurementId: "G-BJGR6HPE48",
});
const db = firebaseConfig.firestore();
export default db;
Using db to get the data from firestore and consoled it:
import db from './firebase';
componentDidMount() {
db.collection("Products").onSnapshot((snap) => console.log(snap));
}
Data is being fetched just fine. You're logging an object whose contents are obfuscated.
snap is a QuerySnapshot type object. You should work with it as you see in the linked API documentation. I also suggest reading the primary product documentation for examples on how to process query results. Minimally, you should iterate the DocumentSnapshot objects contained in that QuerySnapshot, and consider logging the document data within each one.
Here is an example from the documentation:
db.collection("cities").where("state", "==", "CA")
.onSnapshot(function(querySnapshot) {
var cities = [];
querySnapshot.forEach(function(doc) {
cities.push(doc.data().name);
});
console.log("Current cities in CA: ", cities.join(", "));
});
Here is another one using a simpler get() operation rather than a realtime listener:
db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});

'db is undefined' problem with firebase integration in JS

I am doing a small contact form on my personal website. I have a problem with integration of firebase database with form. I read the documentation and watched some YT tutorials and I cannot find the mistake. Could you please take a look? I get a 'db is undefined' error in console.
window.onload = function() {
var firebaseConfig = {
apiKey: "sampleValue",
authDomain: "sampleValue",
databaseURL: "sampleValue",
projectId: "sampleValue",
storageBucket: "sampleValue",
messagingSenderId: "sampleValue",
appId: "sampleValue",
measurementId: "sampleValue"
};
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore;
function submitForm() {
// e.preventDefault();
let nameEl = document.getElementById("InputName");
let emailEl = document.getElementById("InputEmail");
let subjectEl = document.getElementById("InputSubject");
let messageEl = document.getElementById("InputMessage");
let nameValue = nameEl.value;
let emailValue = emailEl.value;
let subjectValue = subjectEl.value;
let messageValue = messageEl.value;
db.collection("contact").doc().set({
name: nameValue,
email: emailValue,
subject: subjectValue,
message: messageValue
})
.then(function() {
alert("dataSaved");
})
.catch(function() {
alert("error");
});
}
document.getElementById("submit").addEventListener("click", submitForm());
};
Edit
I have managed to solve the problem thanks to fellow users #Kevin Peña and #Phix help by:
putting the missing firebase-firestore.js script in index.html
<script defer src="https://www.gstatic.com/firebasejs/7.12.0/firebase-firestore.js"></script>
I had realized that settings in my DB disallowed me to push anything from my form so I have changed the rules to
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Expanding a bit on Phix's comment. Right here:
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore; // <- here
It should be
let db = firebase.firestore()
You can find this on the Guides and on the Reference.
Also, here:
document.getElementById("submit").addEventListener("click", submitForm() /* <-over here */);
You should not call the function, instead pass it to addEventListener (i.e. just its name)
document.getElementById("submit").addEventListener("click", submitForm);
Otherwise the form will be submitted empty when the page loads. And nothing will happen on button click.

how to send data to firebase database in function

I'm trying to send data to firebase. The data is saved to the database after the function is performed, how can I overwrite it during the function execution?
import firebase from 'firebase';
var config = {
apiKey: "xxx",
authDomain: "xxx.firebaseapp.com",
databaseURL: "https://xxx.firebaseio.com",
projectId: "xxx",
storageBucket: "xxx.appspot.com",
messagingSenderId: "xxx"
};
firebase.initializeApp(config);
var db = firebase.database();
var sleep = require('sleep');
function run(TIME) {
db.ref('/test/').child('status').set('1');
sleep.sleep(TIME);
db.ref('/test/').child('status').set('2');
sleep.sleep(TIME);
db.ref('/test/').child('status').set('3');
sleep.sleep(TIME);
db.ref('/test/').child('status').set('4');
};
//========================================<<<< Now I see status in Firebase
run(5);
The set() method is asynchronous and returns a promise that resolves when write to server is complete, as explained in the doc here.
From you comment above I understand you want to have a status "WORKING - before starting function and DONE after".
So you should do something along the following lines:
var status = '';
var adaNameRef = firebase.database().ref('users/ada/name');
status = 'WORKING';
adaNameRef.set({ first: 'Ada', last: 'Lovelace' })
.then(function() {
status = 'DONE';
})
.catch(function(error) {
console.log('Synchronization failed');
});
If you want to "write multiple values to the Database at once", you should use the update() method. See here and here.
Similarly to the set() method, the update() method is asynchronous and returns a promise that resolves when write to server is complete, so you would use the same logic to update the value of status
UPDATE following your comment
1. Send status 'WORKING' to FB 2. Set Relay to ON 3. Wait x seconds 4. Send status 'DONE' to FB 5. Set Relay to OFF
If I understood correctly, this should work (not tested however):
var adaNameRef = firebase.database().ref('users/ada/name');
adaNameRef.set({ status: 'WORKING'})
.then(function() {
// Set Relay to ON ... don't know exactly how you "set the relay"
sleep.sleep(x);
return adaNameRef.set({ status: 'DONE'})
})
.then(function() {
// Set Relay to OFF
})
.catch(function(error) {
console.log(error);
});

firebase database set funtion does not work

This is my code.here set function does not work(value is not updated in firebase database) and no error shown in console.please help me.
var config = {
apiKey: '************************************',
authDomain: 'my-app.firebaseapp.com',
databaseURL: 'https://my-app.firebaseio.com',
storageBucket: 'gs://my-app.appspot.com'
};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
rootRef.set({
'like':'5'
});
firebase database rules as follows
{
"rules": {
".read": true,
".write": true,
"learning": {
"mngmt_quote":
{
},
"Author":{
}
}
}
}
I have tried many methods found in internet.no solution found.please help me
Try this and see if what message you get.
var rootRef = firebase.database().ref();
rootRef.set({
like: '5'
}).then(success => {
console.log('success',success);
},
error => {
console.log('error',error);
}
);

Categories