firebase database set funtion does not work - javascript

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

Related

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

Run something after get value from firebase 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

'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.

Cannot query from Firebase for my React Native app?

It seems I can retrieve all my data from my Firebase Realtime Database with the following:
let itemsRef = firebaseApp.database().ref('/');
itemsRef.on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
But when I try to query with specific parameters instead of just retrieving all the information, I always end up with this error:
#firebase/database: FIREBASE WARNING: Exception was thrown by user callback.
TypeError: Cannot convert undefined or null to object
This is how I'm trying to query information... literally following the documentation, and somehow my code works when I retrieve all information but not when the only change I make is adding a query?
let itemsRef = firebaseApp.database().ref('/');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
Is anyone else having problems querying from Firebase or am I doing something wrong?
This is how my data is structured on Firebase:
I would try initializing firebase in dbConfig.js for instance like so:
import * as firebase from 'firebase';
let config = {
apiKey: "XXXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX"
};
firebase.initializeApp(config);
export default firebase;
I would import firebase where it's:
import firebase from './dbConfig.js'
let itemsRef = firebase.database().ref('/');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
let data = snapshot.val();
let item = Object.values(data);
this.setState({item});
});
Note: OrderByChild the element roundedBPM needs to be a direct child to the root path '/' if it's a nested child you could do something like this:
let itemsRef = firebase.database().ref('/users');
itemsRef.orderByChild('roundedBPM').equalTo('100').on('value', (snapshot) => {
...
});
Note: if you are setting equalTo() roundedBPM when it's a number and not a string you wouldn't get back any data. Make sure you use the correct type of data.
I hope this will help!

Is it possible to define a variable on the firebase database references path?

I am trying to redefine all my apps database references so that I can write a specific set of of firebase rules (I need to add buildings and depts nodes inside the user node – read why: What is the best practice to write the rules of Firebase in a situation like this? ).
I am using a firebase-config.js and exporting all my app's database references to the app's components so hopefully if I change this path I don't have to refactor the code on all the app's components.
I am trying to do it with a function (on my firebase-config.js file):
import * as firebase from "firebase";
import { mapState } from 'vuex';
import { store } from './store/store';
var config = {
apiKey: "XXXXXXXX",
authDomain: "XXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXX",
storageBucket: "XXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXX"
};
firebase.initializeApp(config)
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
let userRef = firebase.database().ref('users').child(user.uid);
let buildingsRef = userRef.child('buildings');
}
})();
export const db = firebase.database();
export const usersRef = db.ref('users');
_// BUT THIS: "buildingsRef" is returning undefined!!! :(
export const buildingsRef = db.ref('users'+ "/" + buildingsRef) //buildingsRef is a variable
export const deptsRef = db.ref('depts');
The buldingsRef variable is returning undefined and it's writing the buildings to an undefined node.
{
"users" : {
"6hwNde08Wuaa9bfReR28niSbOsF3" : {
"name" : "João Alves Marrucho",
"userEmail" : "joaoalvesmarrucho#hotmail.com"
},
"undefined" : {
"-L9M4lM7oZFfmJKorxjC" : {
"address" : "",
"name" : "b1",
"ownerID" : "6hwNde08Wuaa9bfReR28niSbOsF3"
}
}
}
}
I writing to the node with the following method (vue.js):
addBuilding: function () {
let userId = firebase.auth().currentUser.uid;
let buildingKey = buildingsRef.push().key
this.newBuilding.ownerID = userId;
buildingsRef.child(buildingKey).set(this.newBuilding);
}
Any thoughts on why the variable buildingsRef is returning undefined?
Here is my full firebase-config.js file: http://jsfiddle.net/UnXrw/85/
If I understand your question, I think you want something like this:
firebase.auth().onAuthStateChanged(user => {
if (user) {
let userRef = firebase.database().ref('users').child(user.uid);
let buildingsRef = userRef.child('buildings');
// now do whatever you want with those refs
}
});

Categories